JAVAWEB之文件的上传下载
Posted 每天进步一点点,好记性不如烂笔头
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVAWEB之文件的上传下载相关的知识,希望对你有一定的参考价值。
文件上传下载
文件上传:
本篇文章使用的文件上传的例子使用的都是原生技术,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 * <p>初始化上传文件限制参数的监听器</p> 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<Object, Object> prop : properties.entrySet()){ 35 String propertyName = (String) prop.getKey(); 36 String propertyValue = (String) prop.getValue(); 37 38 FileUploadAppProperties.getInstance().addProperty(propertyName, propertyValue); 39 } 40 41 } catch (IOException e) { 42 e.printStackTrace(); 43 } 44 } 45 46 }
6.配置web.xml文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="3.0" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 6 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> 7 <display-name></display-name> 8 <welcome-file-list> 9 <welcome-file>index.jsp</welcome-file> 10 </welcome-file-list> 11 12 <!-- 初始化监听器 --> 13 <listener> 14 <listener-class>com.sunyard.listener.FileUploadAppListener</listener-class> 15 </listener> 16 17 <!-- 注册上传servlet --> 18 <servlet> 19 <servlet-name>upload</servlet-name> 20 <servlet-class>com.sunyard.servlet.FileUploadServlet</servlet-class> 21 </servlet> 22 <servlet-mapping> 23 <servlet-name>upload</servlet-name> 24 <url-pattern>/upload</url-pattern> 25 </servlet-mapping> 26 27 <!-- 注册下载servlet --> 28 <servlet> 29 <servlet-name>download</servlet-name> 30 <servlet-class>com.sunyard.servlet.DownLoadServlet</servlet-class> 31 </servlet> 32 <servlet-mapping> 33 <servlet-name>download</servlet-name> 34 <url-pattern>/download</url-pattern> 35 </servlet-mapping> 36 37 </web-app>
配置监听器,以及文件上传servlet和文件下载servlet。
6.完善工程所需要的类,
1)创建上传下载实体,FileUploadBean
1 package com.sunyard.bean; 2 3 /** 4 * <p>文件上传实体</p> 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.fileDesc = 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 * <p>文件上传下载dao</p> 14 * @author:774346810@qq.com 15 * @date:2017-6-25 16 */ 17 public class UploadFileDao { 18 19 /** 20 * 查询所有文件信息 21 * @return 22 */ 23 public List<FileUploadBean> getFiles(){ 24 Connection conn = null; 25 Statement statement = null; 26 ResultSet rs = null; 27 28 List<FileUploadBean> beans = new ArrayList<FileUploadBean>(); 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, fileName, 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<FileUploadBean> 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 < uploadFiles.size();i++){ 71 FileUploadBean fileUploadBean = uploadFiles.get(i); 72 preparedStatement.setString(1, fileUploadBean.getFileName()); 73 preparedStatement.setString(2, fileUploadBean.getFilePath()); 74 preparedStatement.setString(3, fileUploadBean.getFileDesc()); 75 preparedStatement.executeUpdate(); 76 } 77 78 } catch (Exception e) { 79 e.printStackTrace(); 80 } finally{ 81 JDBCUtils.release(null, preparedStatement, conn); 82 } 83 84 } 85 }
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<String, FileItem> uploadFiles = new HashMap<String, FileItem>(); 54 55 //解析请求, 得到 FileItem 的集合. 56 List<FileItem> items = upload.parseRequest(request); 57 58 //1. 构建 FileUploadBean 的集合, 同时填充 uploadFiles 59 List<FileUploadBean> 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<FileUploadBean> beans) { 81 uploadFileDao.save(beans); 82 } 83 84 /** 85 * 进行文件上传操作 86 * @param uploadFiles 87以上是关于JAVAWEB之文件的上传下载的主要内容,如果未能解决你的问题,请参考以下文章