文件上传:
本篇文章使用的文件上传的例子使用的都是原生技术,servelt+jdbc+fileupload插件,这也是笔者的习惯,当接触到某些从未接触过的东西时,总是喜欢用最原始的东西将他们表达出来。下面是具体的步骤,大家可以跟着我一步一步的用apache的fileupload插件来完成文件的上传下载。
1.创建一个web工程,我们这里取名为fileupload
2.导入相关jar包,
,数据源使用的是apache-c3p0数据源,以及上传下载插件包,goson库,以及mysql驱动包,大家可以去https://mvnrepository.com/自行下载,系在前请核实jar版本,防止jar冲突。
3.src目录下创建upload.properties文件,用于配置文件上传的限制参数。
1 exts=pptx,docx,doc
2 file.max.size=1048576
3 total.file.max.size=5242880
4.创建工程包结构,
5.创建读取upload.properties的监听器类,初始化上传文件的限制参数,具体代码如下:
1 package com.sunyard.listener;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.util.Map;
6 import java.util.Properties;
7
8 import javax.servlet.ServletContextEvent;
9 import javax.servlet.ServletContextListener;
10
11 import com.sunyard.utils.FileUploadAppProperties;
12
13 /**
14 * 初始化上传文件限制参数的监听器
15 * @author:774346810@qq.com
16 * @date:2017-6-16
17 */
18 public class FileUploadAppListener implements ServletContextListener{
19
20 @Override
21 public void contextDestroyed(ServletContextEvent arg0) {
22
23 }
24
25 @Override
26 public void contextInitialized(ServletContextEvent arg0) {
27 InputStream in = this.getClass().getClassLoader().getResourceAsStream("/upload.properties");
28
29 Properties properties = new Properties();
30
31 try {
32 properties.load(in);
33
34 for(Map.Entry
6.配置web.xml文件
1
2
7
8
9 index.jsp
10
11
12
13
14 com.sunyard.listener.FileUploadAppListener
15
16
17
18
19 upload
20 com.sunyard.servlet.FileUploadServlet
21
22
23 upload
24 /upload
25
26
27
28
29 download
30 com.sunyard.servlet.DownLoadServlet
31
32
33 download
34 /download
35
36
37
配置监听器,以及文件上传servlet和文件下载servlet。6.完善工程所需要的类,
1)创建上传下载实体,FileUploadBean
1 package com.sunyard.bean;
2
3 /**
4 * 文件上传实体
5 * @author:774346810@qq.com
6 * @date:2017-6-16
7 */
8 public class FileUploadBean {
9 private Integer id;
10 // 文件名
11 private String fileName;
12 // 文件的路径
13 private String filePath;
14 // 文件的描述
15 private String fileDesc;
16
17 public Integer getId() {
18 return id;
19 }
20
21 public void setId(Integer id) {
22 this.id = id;
23 }
24
25 public String getFileName() {
26 return fileName;
27 }
28
29 public void setFileName(String fileName) {
30 this.fileName = fileName;
31 }
32
33 public String getFilePath() {
34 return filePath;
35 }
36
37 public void setFilePath(String filePath) {
38 this.filePath = filePath;
39 }
40
41 public String getFileDesc() {
42 return fileDesc;
43 }
44
45 public void setFileDesc(String fileDesc) {
46 this.fileDesc = fileDesc;
47 }
48
49 public FileUploadBean(String fileName, String filePath, String fileDesc) {
50 super();
51 this.fileName = fileName;
52 this.filePath = filePath;
53 this.fileDesc = fileDesc;
54 }
55
56 public FileUploadBean(Integer id, String fileName, String filePath,
57 String fileDesc) {
58 this.id = id;
59 this.fileName = fileName;
60 this.filePath = filePath;
61 this.fileDe服务器托管网sc = fileDesc;
62 }
63
64 public FileUploadBean() {
65
66 }
67 }
2)dao操作自定义异常类
1 package com.sunyard.db;
2
3 public class DBException extends Exception {
4
5 /**
6 *
7 */
8 private static final long serialVersionUID = -1547402862446161034L;
9
10 public DBException() {
11 }
12
13 public DBException(String msg) {
14 super(msg);
15 }
16
17 public DBException(String msg, Exception ex) {
18 super(msg, ex);
19 }
20 }
3)JDBC连接工具类
1 package com.sunyard.db;
2
3 import java.io.InputStream;
4 import java.sql.Connection;
5 import java.sql.DriverManager;
6 import java.sql.ResultSet;
7 import java.sql.SQLException;
8 import java.sql.Statement;
9 import java.util.Properties;
10
11 public class JDBCUtils {
12 public static void release(ResultSet rs,
13 Statement statement, Connection conn) {
14 if(rs != null){
15 try {
16 rs.close();
17 } catch (SQLException e) {
18 e.printStackTrace();
19 }
20 }
21
22
23 if (statement != null) {
24 try {
25 statement.close();
26 } catch (Exception e2) {
27 e2.printStackTrace();
28 }
29 }
30
31 if (conn != null) {
32 try {
33 conn.close();
34 } catch (Exception e2) {
35 e2.printStackTrace();
36 }
37 }
38 }
39
40 /**
41 * 关闭 Statement 和 Connection
42 * @param statement
43 * @param conn
44 */
45 public static void release(Statement statement, Connection conn) {
46 if (statement != null) {
47 try {
48 statement.close();
49 } catch (Exception e2) {
50 e2.printStackTrace();
51 }
52 }
53
54 if (conn != null) {
55 try {
56 conn.close();
57 } catch (Exception e2) {
58 e2.printStackTrace();
59 }
60 }
61 }
62
63 /**
64 * 1. 获取连接的方法. 通过读取配置文件从数据库服务器获取一个连接.
65 *
66 * @return
67 * @throws Exception
68 */
69 public static Connection getConnection() throws Exception {
70 // 1. 准备连接数据库的 4 个字符串.
71 // 1). 创建 Properties 对象
72 Properties properties = new Properties();
73
74 // 2). 获取 jdbc.properties 对应的输入流
75 InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream(
76 "jdbc.properties");
77
78 // 3). 加载 2) 对应的输入流
79 properties.load(in);
80
81 // 4). 具体决定 user, password 等4 个字符串.
82 String user = properties.getProperty("user");
83 String password = properties.getProperty("password");
84 String jdbcUrl = properties.getProperty("jdbcUrl");
85 String driver = properties.getProperty("driver");
86
87 // 2. 加载数据库驱动程序(对应的 Driver 实现类中有注册驱动的静态代码块.)
88 Class.forName(driver);
89
90 // 3. 通过 DriverManager 的 getConnection() 方法获取数据库连接.
91 return DriverManager.getConnection(jdbcUrl, user, password);
92 }
93 }
5)文件上传下载的dao层方法
1 package com.sunyard.db;
2
3 import java.sql.Connection;
4 import java.sql.ResultSet;
5 import java.util.ArrayList;
6 import java.util.List;
7
8 import com.mysql.jdbc.PreparedStatement;
9 import com.mysql.jdbc.Statement;
10 import com.sunyard.bean.FileUploadBean;
11
12 /**
13 * 文件上传下载dao
14 * @author:774346810@qq.com
15 * @date:2017-6-25
16 */
17 public class UploadFileDao {
18
19 /**
20 * 查询所有文件信息
21 * @return
22 */
23 public List getFiles(){
24 Connection conn = null;
25 Statement statement = null;
26 ResultSet rs = null;
27
28 List beans = new ArrayList();
29
30 try {
31 conn = JDBCUtils.getConnection();
32 String sql = "SELECT id, file_name fileName, file_path filePath, " +
33 "file_desc fileDesc FROM upload_files";
34 statement = (Statement) conn.createStatement();
35 rs = statement.executeQuery(sql);
36
37 while(rs.next()){
38 Integer id = rs.getInt("id");
39 String fileName = rs.getString("file_name");
40 String filePath = rs.getString("file_path");
41 String fileDesc = rs.getString("file_desc");
42
43 FileUploadBean bean = new FileUploadBean(id, fil服务器托管网eName, filePath, fileDesc);
44 beans.add(bean);
45 }
46 } catch (Exception e) {
47 e.printStackTrace();
48 } finally{
49 JDBCUtils.release(rs, statement, conn);
50 }
51
52 return beans;
53 }
54
55 /**
56 * 将已经上传的文件存放数据库中
57 * @param uploadFiles
58 */
59 public void save(List uploadFiles){
60
61 Connection conn = null;
62 PreparedStatement preparedStatement = null;
63
64 try {
65 conn = JDBCUtils.getConnection();
66 String sql = "INSERT INTO upload_files (file_name, file_path, file_desc) VALUES " +
67 "(?, ?, ?)";
68 preparedStatement = (PreparedStatement) conn.prepareStatement(sql);
69
70 for(int i = 0;i
6)自定义异常类
1 package com.sunyard.exception;
2
3 public class InvalidExtNameException extends RuntimeException{
4
5 /**
6 *
7 */
8 private static final long serialVersionUID = -1478119693559275850L;
9
10 public InvalidExtNameException(String msg){
11 super(msg);
12 }
13 }
7)处理文件上传的servlet
1 package com.sunyard.servlet;
2
3 import java.io.File;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8 import java.io.UnsupportedEncodingException;
9 import java.util.ArrayList;
10 import java.util.Arrays;
11 import java.util.HashMap;
12 import java.util.List;
13 import java.util.Map;
14 import java.util.Random;
15
16 import javax.servlet.ServletException;
17 import javax.servlet.http.HttpServlet;
18 import javax.servlet.http.HttpServletRequest;
19 import javax.servlet.http.HttpServletResponse;
20
21 import org.apache.commons.fileupload.FileItem;
22 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
23 import org.apache.commons.fileupload.servlet.ServletFileUpload;
24
25 import com.sunyard.bean.FileUploadBean;
26 import com.sunyard.db.UploadFileDao;
27 import com.sunyard.exception.InvalidExtNameException;
28 import com.sunyard.utils.FileUploadAppProperties;
29
30 public class FileUploadServlet extends HttpServlet{
31
32 private static final long serialVersionUID = 6227133615299280663L;
33
34 private static final String FILE_PATH = "/WEB-INF/files/";//类路径
35
36 private static final String TEMP_DIR = "d:tempDirectory";//文件临时存储路径
37
38 UploadFileDao uploadFileDao = new UploadFileDao();
39
40 @Override
41 protected void doPost(HttpServletRequest request, HttpServletResponse response)
42 throws ServletException, IOException {
43 request.setCharacterEncoding("UTF-8");
44
45 String path = null;
46
47 //获取 ServletFileUpload 对象.
48 ServletFileUpload upload = getServletFileUpload();
49
50 try {
51 //把需要上传的 FileItem 都放入到该 Map 中
52 //键: 文件的待存放的路径, 值: 对应的 FileItem 对象
53 Map uploadFiles = new HashMap();
54
55 //解析请求, 得到 FileItem 的集合.
56 List items = upload.parseRequest(request);
57
58 //1. 构建 FileUploadBean 的集合, 同时填充 uploadFiles
59 List beans = buildFileUploadBeans(items, uploadFiles);
60
61 //2. 校验扩展名:
62 vaidateExtName(beans);
63
64 //3. 校验文件的大小: 在解析时, 已经校验了, 我们只需要通过异常得到结果.
65
66 //4. 进行文件的上传操作.
67 upload(uploadFiles);
68
69 //5. 把上传的信息保存到数据库中
70 saveBeans(beans);
71
72 path = "/app/success.jsp";
73 } catch (Exception e) {
74 e.printStackTrace();
75 }
76
77 request.getRequestDispatcher(path).forward(request, response);
78 }
79
80 private void saveBeans(List beans) {
81 uploadFileDao.save(beans);
82 }
83
84 /**
85 * 进行文件上传操作
86 * @param uploadFiles
87 * @throws IOException
88 */
89 private void upload(Map uploadFiles) throws IOException {
90 for(Map.Entry uploadFile: uploadFiles.entrySet()){
91 String filePath = uploadFile.getKey();
92 FileItem item = uploadFile.getValue();
93
94 upload(filePath, item.getInputStream());
95 }
96 }
97
98 /**
99 * 文件上传的 IO 方法.
100 *
101 * @param filePath
102 * @param inputStream
103 * @throws IOException
104 */
105 private void upload(String filePath, InputStream inputStream) throws IOException {
106 OutputStream out = new FileOutputStream(filePath);
107
108 byte [] buffer = new byte[1024];
109 int len = 0;
110
111 while((len = inputStream.read(buffer)) != -1){
112 out.write(buffer, 0, len);
113 }
114
115 inputStream.close();
116 out.close();
117
118 System.out.println(filePath);
119 }
120
121 /**
122 * 校验文件扩展名是否合法
123 * @param beans
124 */
125 private void vaidateExtName(List beans) {
126 String exts = FileUploadAppProperties.getInstance().getProperty("exts");
127 List extList = Arrays.asList(exts.split(","));
128 System.out.println(extList);
129
130 for(FileUploadBean bean: beans){
131 String fileName = bean.getFileName();
132 System.out.println(fileName.indexOf("."));
133
134 String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
135 System.out.println(extName);
136
137 if(!extList.contains(extName)){
138 throw new InvalidExtNameException(fileName + "文件的扩展名不合法");
139 }
140 }
141 }
142
143 /**
144 * 利用传入的 FileItem 的集合, 构建 FileUploadBean 的集合, 同时填充 uploadFiles
145 *
146 * FileUploadBean 对象封装了: id, fileName, filePath, fileDesc
147 * uploadFiles: Map 类型, 存放文件域类型的 FileItem. 键: 待保存的文件的名字 ,值: FileItem 对象
148 *
149 * 构建过程:
150 * 1. 对传入 FileItem 的集合进行遍历. 得到 desc 的那个 Map. 键: desc 的 fieldName(desc1, desc2 ...).
151 * 值: desc 的那个输入的文本值
152 *
153 * 2. 对传入 FileItem 的集合进行遍历. 得到文件域的那些 FileItem 对象, 构建对应的 key (desc1 ....) 来获取其 desc.
154 * 构建的 FileUploadBean 对象, 并填充 beans 和 uploadFiles
155 *
156 * @param items
157 * @param uploadFiles
158 * @return
159 * @throws UnsupportedEncodingException
160 */
161 private List buildFileUploadBeans(List items,
162 Map uploadFiles) throws UnsupportedEncodingException {
163 List beans = new ArrayList();
164
165 Map descs = new HashMap();
166
167 //处理普通的表单体
168 for(int i = 0;i
8)用于存储文件上传的单例工具类FileUploadAppProperties
1 package com.sunyard.utils;
2
3 import java.util.HashMap;
4 import java.util.Map;
5
6 /**
7 * 上传下载参数单例类
8 * @author:774346810@qq.com
9 * @date:2017-6-16
10 */
11 public class FileUploadAppProperties {
12
13 private Map properties = new HashMap();
14
15 private FileUploadAppProperties(){}
16
17 private static FileUploadAppProperties instance = new FileUploadAppProperties();
18
19 public static FileUploadAppProperties getInstance(){
20 return instance;
21 }
22
23 public void addProperty(String propertyName,String propertyValue){
24 properties.put(propertyName, propertyValue);
25 }
26
27 public String getProperty(String propertyName){
28 return properties.get(propertyName);
29 }
30 }
9)JDBC连接数据库的参数properties文件
1 #driver=oracle.jdbc.driver.OracleDriver
2 #jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl
3 #user=scott
4 #password=java
5
6 driver=com.mysql.jdbc.Driver
7 jdbcUrl=jdbc:mysql://localhost:3306/upload
8 user=root
9 password=123456
10)jQuery开发的静态资源文件
11)文件上传的页面upload.jsp
1
2
6
7
8
9
10
11
12 My JSP 'upload.jsp' starting page
13
14
15
16
17
18
19
22
23
24
25 $(function(){
26
27 var i = 2;
28
29 $("#addFile").click(function(){
30 $(this).parent().parent().before("File"
31 + i + ": "
33 + " Desc"
34 + i + ":