java-上传文件与现实上传文件

项目结构:

 

项目展示:

 

数据库:

/*
SQLyog Ultimate v12.09 (64 bit)
MySQL - 5.5.53 : Database - fileupload
*********************************************************************
*//*!40101 SET NAMES utf8 */;/*!40101 SET SQL_MODE=''*/;/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`fileupload` /*!40100 DEFAULT CHARACTER SET utf8 */;USE `fileupload`;/*Table structure for table `fileupload` */DROP TABLE IF EXISTS `fileupload`;CREATE TABLE `fileupload` (`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',`name` varchar(255) DEFAULT NULL COMMENT '产品名称',`path` varchar(255) DEFAULT NULL COMMENT '产品存储路径',`realname` varchar(255) DEFAULT NULL COMMENT '产品描述图片真实名称',PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8;/*Data for the table `fileupload` */insert  into `fileupload`(`id`,`name`,`path`,`realname`) values (20,'jack','/2017/8/16/cfd0d04e92714dcdb08c64c9db5fa638.jpg','jklh.jpg'),(21,'小米','/2017/8/16/72ee3800c2e44679a5df17a083f7759d.jpg','timg.jpg');/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

 

-------------------------------

代码:

com.gordon.dao:

--ProductDao.java

package com.gordon.dao;import java.sql.SQLException;
import java.util.List;import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;import com.gordon.domain.Product;
import com.gordon.utils.DataSourceUtil;public class ProductDao {/*** 添加产品* @param product_name* @param fileRealName* @param saveDbPath* @return* @throws SQLException */public int addProduct(String product_name, String fileRealName, String saveDbPath) throws SQLException {QueryRunner qr = new QueryRunner(DataSourceUtil.getDataSource());String sql = "INSERT INTO fileupload (name,realname, path) VALUES (?, ?, ?)";return qr.update(sql, product_name, fileRealName, saveDbPath);}/*** * @return* @throws SQLException */public List<Product> getAllProduct() throws SQLException {QueryRunner qr = new QueryRunner(DataSourceUtil.getDataSource());String sql = "select * from fileupload";return qr.query(sql, new BeanListHandler<Product>(Product.class));}}

 

com.gordon.domain:
--Product.java

package com.gordon.domain;public class Product {private int id;private String name;private String realname;private String path;public Product() {}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getRealname() {return realname;}public void setRealname(String realname) {this.realname = realname;}public String getPath() {return path;}public void setPath(String path) {this.path = path;}
}

 

com.gordon.service:
--ProductService.java

package com.gordon.service;import java.sql.SQLException;
import java.util.List;import com.gordon.dao.ProductDao;
import com.gordon.domain.Product;public class ProductService {/*** 添加产品* @param product_name* @param fileRealName* @param saveDbPath* @return* @throws SQLException */public int addProduct(String product_name, String fileRealName, String saveDbPath) throws SQLException {return new ProductDao().addProduct(product_name, fileRealName, saveDbPath);}/*** 获取所有商品* @return * @throws SQLException */public List<Product> getAllProduct() throws SQLException {return new ProductDao().getAllProduct();}}

 

com.gordon.utils:

--DataSourceUtil.java

package com.gordon.utils;import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;import javax.sql.DataSource;import com.mchange.v2.c3p0.ComboPooledDataSource;public class DataSourceUtil {private static ComboPooledDataSource ds = new ComboPooledDataSource();/*** 获取数据源* * @return 连接池*/public static DataSource getDataSource() {return ds;}/*** 获取连接* * @return 连接* @throws SQLException*/public static Connection getConnection() throws SQLException {return ds.getConnection();}/*** 释放资源* * @param conn*            连接* @param st*            语句执行者* @param rs*            结果集*/public static void closeResource(Connection conn, Statement st, ResultSet rs) {closeResultSet(rs);closeStatement(st);closeConn(conn);}/*** 释放连接* * @param conn*            连接*/public static void closeConn(Connection conn) {if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}conn = null;}}/*** 释放语句执行者* * @param st*            语句执行者*/public static void closeStatement(Statement st) {if (st != null) {try {st.close();} catch (SQLException e) {e.printStackTrace();}st = null;}}/*** 释放结果集* * @param rs*            结果集*/public static void closeResultSet(ResultSet rs) {if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}rs = null;}}
}

 

com.gordon.web.servlet:

--AddProductServlet.java

package com.gordon.web.servlet;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.UUID;import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;import org.apache.commons.io.IOUtils;import com.gordon.service.ProductService;/*** 添加产品*/
@WebServlet("/addProduct")
@MultipartConfig
public class AddProductServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8");String product_name = request.getParameter("name");Part part = request.getPart("file");// 获取真实文件名称String fileRealName = this.getFileRealName(part);// 获取服务器上的绝对存储路径与数据库上的相对路径String[] savePath = this.getSavePath(request, fileRealName);int res = 0;try {// 上传文件this.uploadFile(part, savePath[0]);// 将数据存入数据库res = new ProductService().addProduct(product_name, fileRealName, savePath[1]);} catch (Exception e) {e.printStackTrace();}if (res != 1) {request.setAttribute("msg", "添加文件失败!");request.getRequestDispatcher("/error_page.jsp").forward(request, response);}response.sendRedirect(request.getContextPath() + "/showProduct");}/*** 获取保存路径 [0] 服务器存储路径 [1]数据库存储路径* * @param request* @param fileRealName* @return*/private String[] getSavePath(HttpServletRequest request, String fileRealName) {// 获取存储时的随机产品名称String randomFilePath = this.getRandomFileName(fileRealName);// 获取存储绝对路径String savepath = request.getServletContext().getRealPath("/upload");// 获取存储目录 如:/2017/12/23/ 2017-12-23String savedir = this.getSaveDir();// 最终存储路径String saveWebPosition = savepath + savedir;String saveDbPosition = savedir;// 服务器文件夹不存在则创建File file = new File(saveWebPosition);if (!file.exists()) {file.mkdirs();}String[] res = { saveWebPosition + randomFilePath, saveDbPosition + randomFilePath };return res;}/*** 获取存储目录* * @return*/private String getSaveDir() {Calendar now = Calendar.getInstance();int year = now.get(Calendar.YEAR);int month = now.get(Calendar.MONTH) + 1;int day = now.get(Calendar.DAY_OF_MONTH);return ("/" + year + "/" + month + "/" + day + "/").toString();}/*** 获取上传文件名称* * @param part* @return*/private String getFileRealName(Part part) {String contentDisposition = part.getHeader("Content-Disposition");String filerealname = contentDisposition.substring(contentDisposition.lastIndexOf("filename="));return filerealname.substring(10, filerealname.length() - 1);}/*** 上传文件* * @param part*/private void uploadFile(Part part, String saveWebPath) throws Exception {InputStream is = part.getInputStream();FileOutputStream os = new FileOutputStream(saveWebPath);IOUtils.copy(is, os);is.close();os.close();part.delete();}/*** 获取随机产品名称* * @param part* @return*/private String getRandomFileName(String fileRealName) {String fileSuffix = fileRealName.substring(fileRealName.lastIndexOf("."));String randomName = UUID.randomUUID().toString().replace("-", "").toLowerCase();return randomName + fileSuffix;}
}

 

--ShowProductServlet.java

package com.gordon.web.servlet;import java.io.IOException;
import java.sql.SQLException;
import java.util.List;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import com.gordon.domain.Product;
import com.gordon.service.ProductService;/*** 展示数据*/
@WebServlet("/showProduct")
public class ShowProductServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {List<Product> list = null;try {list = new ProductService().getAllProduct();} catch (SQLException e) {e.printStackTrace();}request.setAttribute("list", list);request.getRequestDispatcher("/show_product.jsp").forward(request, response);}protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}
}

 

c3p0-config.xml

<c3p0-config><!-- 默认配置,如果没有指定则使用这个配置 --><default-config><!-- 基本配置 --><property name="driverClass">com.mysql.jdbc.Driver</property><property name="jdbcUrl">jdbc:mysql://localhost:3306/fileupload</property><property name="user">root</property><property name="password">root</property><!--扩展配置--><property name="checkoutTimeout">30000</property><property name="idleConnectionTestPeriod">30</property><property name="initialPoolSize">10</property><property name="maxIdleTime">30</property><property name="maxPoolSize">100</property><property name="minPoolSize">10</property><property name="maxStatements">200</property></default-config> <!-- 命名的配置 --><named-config name="itcast"><property name="driverClass">com.mysql.jdbc.Driver</property><property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/xxxx</property><property name="user">root</property><property name="password">1234</property><!-- 如果池中数据连接不够时一次增长多少个 --><property name="acquireIncrement">5</property><property name="initialPoolSize">20</property><property name="minPoolSize">10</property><property name="maxPoolSize">40</property><property name="maxStatements">20</property><property name="maxStatementsPerConnection">5</property></named-config>
</c3p0-config> 

 

-------------------------------

add_product.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><form action="${ pageContext.request.contextPath }/addProduct" method="post"enctype="multipart/form-data"><table><tr><td>产品名称:</td><td><input type="text" name="name" /></td></tr><tr><td>产品图片:</td><td><input type="file" name="file" /></td></tr><tr><td colspan="2"><input type="submit" value="添加产品" /></td></tr></table></form>
</body>
</html>

 

error_page.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>${ msg }
</body>
</html>

 

index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><a href="${ pageContext.request.contextPath }/add_product.jsp">添加产品</a>
</body>
</html>

 

show_product.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body><table border="1"><tr><td>id</td><td>产品名称</td><td>产品展示</td></tr><c:forEach var="p" items="${ list }"><tr><td>${ p.id }</td><td>${ p.name }</td><td><img alt="" width="100" height="100" src="${ pageContext.request.contextPath}/upload${ p.path }"></td></tr></c:forEach></table>
</body>
</html>

 

转载于:https://www.cnblogs.com/hfultrastrong/p/7374065.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/428902.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

1012 数字分类 (20 分)

1012 数字分类 (20 分) 给定一系列正整数&#xff0c;请按要求对数字进行分类&#xff0c;并输出以下 5 个数字&#xff1a; A ​1 ​​ 能被 5 整除的数字中所有偶数的和&#xff1b; A ​2 ​​ 将被 5 除后余 1 的数字按给出顺序进行交错求和&#xff0c;即计算 n ​1 ​…

BZOJ2948 : [Poi2001]绿色游戏

维护一个保护集合$S$&#xff0c;表示哪些点$A$可能胜利。 首先将所有绿点加入$S$。 $1.$对于一个不在$S$的$A$点&#xff0c;若它存在某个后继在$S$中&#xff0c;则将其加入$S$。 $2.$对于一个不在$S$的$B$点&#xff0c;若它所有后继都在$S$中&#xff0c;则将其加入$S$。 通…

登录微信用android设备,Android 之微信登录

准备工作需要在微信开放平台注册登录账户。还得办理开发者资质认证&#xff0c;审核费用为300元。2.在微信开放平台创建移动应用&#xff0c;填写相关信息后提交审核。简述业务流程1.获取appId和secret2.通过appId和secret调微信接口获取 code3.通过code和getAccessToken()方法…

1013 数素数 (20 分)

1013 数素数 (20 分) 令 P ​i ​​ 表示第 i 个素数。现任给两个正整数 M≤N≤10 ​4 ​​ &#xff0c;请输出 P ​M ​​ 到 P ​N ​​ 的所有素数。 输入格式&#xff1a; 输入在一行中给出 M 和 N&#xff0c;其间以空格分隔。 输出格式&#xff1a; 输出从 P ​M ​​…

《浅谈CT》总结

注明来自 http://www.ssdfans.com/?p1941 这里说的CT&#xff0c;不是医院里面的CT&#xff0c;而是闪存的一种技术&#xff1a;Charge Trap。 闪存不只有Floating Gate&#xff0c;还有Charge Trap。 浮栅极材料是导体&#xff0c;一般为多晶硅。 CTF&#xff08;Charge Trap…

android可见区域,识别目标View在HorizontalScrollView可见区域

完成需求的时候涉及到这个所以撸了一下本文章是本人原创&#xff0c;转载请带原地址连接先放效果图(霁雪清虹"是目标)&#xff1a;首先需要一个自定义HorizontalScrollView&#xff0c;复写一个View的onScrollChanged方法&#xff0c;用于监听滑动变化代码如下&#xff1a…

1015 德才论 (25 分)

1015 德才论 (25 分) 宋代史学家司马光在《资治通鉴》中有一段著名的“德才论”&#xff1a;“是故才德全尽谓之圣人&#xff0c;才德兼亡谓之愚人&#xff0c;德胜才谓之君子&#xff0c;才胜德谓之小人。凡取人之术&#xff0c;苟不得圣人&#xff0c;君子而与之&#xff0c…

AI单挑Dota 2世界冠军:被电脑虐哭……

OpenAI的机器人刚刚在 Dota2 1v1 比赛中战胜了人类顶级职业玩家 Denti。以建设安全的通用人工智能为己任的 OpenAI&#xff0c;通过“Self-Play”的方式&#xff0c;从零开始训练出了这个机器人。 Dota2沦陷 继横扫顶级的人类国际象棋大师和围棋大师后&#xff0c;计算机如今在…

用session实现html登录页面跳转页面跳转页面跳转,js判断登录与否并确定跳转页面的方法...

这篇文章主要介绍了js判断登录与否并确定跳转页面的方法,涉及Ajax及session使用的技巧,非常具有实用价值,需要的朋友可以参考下本文实例讲述了js判断登录与否并确定跳转页面的方法。分享给大家供大家参考。具体如下&#xff1a;使用session存储&#xff0c;确定用户是否登录&am…

7-26 Windows消息队列(25 分)

7-26 Windows消息队列&#xff08;25 分&#xff09; 消息队列是 Windows 系统的基础。对于每个进程&#xff0c;系统维护一个消息队列。如果在进程中有特定事件发生&#xff0c;如点击鼠标、文字改变等&#xff0c;系统将把这个消息加到队列当中。同时&#xff0c;如果队列不…

Java——操作集合的工具类:Collections

Java 提供了一个操作 Set 、List 和 Map 等集合的工具类 &#xff1a;Collections&#xff0c;该工具类里提供了大量方法对集合元素进行排序、查询和修改等操作 转载于:https://www.cnblogs.com/szj-ang/p/7383027.html

鸿蒙关键技术研究,华为鸿蒙 2.0 系统主题演讲公布,详细架构 9 月 11 日揭晓

IT之家 8 月 30 日消息 华为 9 月 10 日将举行华为开发者大会 2020&#xff0c;华为官网表示&#xff0c;“我们将与您分享 HMS Core 5.0 最新进展&#xff0c; 揭开 HarmonyOS 和 EMUI 11 的神秘面纱。 振奋人心的新技术&#xff0c;深入的交流学习机会&#xff0c; 更灵动的想…

shell 提示符个性化设置

提示符具体含义可参考&#xff1a; http://billie66.github.io/TLCL/book/zh/chap14.html Ubuntu16.04个人配置如下&#xff0c;供以后查阅 1 function git_branch {2 branch"git branch 2>/dev/null | grep "^\*" | sed -e "s/^\*\ //""3…

如何设置鼠标滚轮html,win7如何设置鼠标滚轮

你们知道在W7中怎么设置鼠标的滚轮吗?下面是小编带来的关于win7如何设置鼠标滚轮的内容&#xff0c;欢迎阅读!Win7设置滚轮方法一&#xff1a;首先要在电脑的左下角点击开始按钮点击开始按钮以后出现上拉菜单&#xff0c;在菜单上面点击控制面板点击控制面板以后进入到控制面板…

湛江高考2021成绩查询,2021广东省高中学业水平考试成绩查询(入口+方式)

2021年广东高中学业水平合格性考试成绩查询查询方式&#xff1a;考生登录广东省教育考试服务中心的广东教育考试服务网&#xff0c;通过综合查询栏目页面&#xff0c;按相关提示即可查询考试成绩。查询入口二&#xff1a;“广东省教育考试院”小程序查询方式&#xff1a;①在“…

A. Red and Blue Beans

题意&#xff1a;红豆子和绿豆子分在不同的篮子里。问最小的最大差是能不能比给的d小。 方法&#xff1a;尽可能用更多的篮子里。 #include<iostream> using namespace std; int main() {double a,b,k;int n;cin>>n;for (int i0;i<n;i){cin>>a>>b&…

JAVA经典算法40题

【程序1】 题目&#xff1a;古典问题&#xff1a;有一对兔子&#xff0c;从出生后第3个月起每个月都生一对兔子&#xff0c;小兔子长到第四个月后每个月又生一对兔子&#xff0c;假如兔子都不死&#xff0c;问每个月的兔子总数为多少&#xff1f; 1.程序分析&#xff1a; 兔子…

中英对照 关于计算机的科技英语,《计算机专业英语》(中英文对照).pdf

《计算机专业英语》(中英文对照)计算机专业英语Computer EnglishChapter 1 The History andFuture of Computers2009.9.1Chapter 1 The History and Future of ComputersKey points:Key points:useful terms and definitions ofuseful terms and definitions ofcomputerscomput…

[php] in_array 判断问题(坑)

<?php $arr array("Linux"); if (in_array(0, $arr)) {echo "match"; } ?> 执行以上代码&#xff0c;0和字符串是可以匹配成功的。 原因是在in_array&#xff0c;如果比较的类型不匹配&#xff0c;并且第一个参数是0&#xff0c;它会返回true&…

B. The Cake Is a Lie

题意&#xff1a;从&#xff08;1&#xff0c;1&#xff09;走到他给的点&#xff0c;只能向上和向右。int cou 0;如果向上就coux;,如果向右就couy; 题解&#xff1a;最大的cou是两条直线。最小的cou是一直转弯。 注意点&#xff1a;如果x>y 先走x;反之亦反&#xff1b; #i…