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 * @throws IOException 88 */ 89 private void upload(Map<String, FileItem> uploadFiles) throws IOException { 90 for(Map.Entry<String, FileItem> 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<FileUploadBean> beans) { 126 String exts = FileUploadAppProperties.getInstance().getProperty("exts"); 127 List<String> 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<String, FileItem> 类型, 存放文件域类型的 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<FileUploadBean> buildFileUploadBeans(List<FileItem> items, 162 Map<String, FileItem> uploadFiles) throws UnsupportedEncodingException { 163 List<FileUploadBean> beans = new ArrayList<FileUploadBean>(); 164 165 Map<String, String> descs = new HashMap<String, String>(); 166 167 //处理普通的表单体 168 for(int i = 0;i < items.size();i++){ 169 FileItem item = items.get(i); 170 171 if(item.isFormField()){ 172 //desc1 或 desc2 ... 173 String fieldName = item.getFieldName(); 174 String desc = item.getString("UTF-8"); 175 176 descs.put(fieldName, desc); 177 } 178 } 179 180 //处理文件表单体 181 for(int i = 0;i < items.size();i++){ 182 FileItem item = items.get(i); 183 FileUploadBean bean = null; 184 if(!item.isFormField()){ 185 String fieldName = item.getFieldName(); 186 String descName = "desc" + fieldName.substring(fieldName.length() - 1); 187 String desc = descs.get(descName); 188 189 //对应文件名 190 String fileName = item.getName(); 191 String filePath = getFilePath(fileName); 192 193 bean = new FileUploadBean(fileName, filePath, desc); 194 beans.add(bean); 195 196 uploadFiles.put(bean.getFilePath(), item); 197 } 198 } 199 200 return beans; 201 } 202 203 /** 204 * 根据跟定的文件名构建一个随机的文件名 205 * 1. 构建的文件的文件名的扩展名和给定的文件的扩展名一致 206 * 2. 利用 ServletContext 的 getRealPath 方法获取的绝对路径 207 * 3. 利用了 Random 和 当前的系统时间构建随机的文件的名字 208 * 209 * @param fileName 210 * @return 211 */ 212 private String getFilePath(String fileName) { 213 String extName = fileName.substring(fileName.lastIndexOf(".")); 214 Random random = new Random(); 215 216 String filePath = getServletContext().getRealPath(FILE_PATH) + "\\" + System.currentTimeMillis() + random.nextInt(100000) + extName; 217 return filePath; 218 } 219 220 /** 221 * 获取 ServletFileUpload 对象. 222 * @return 223 */ 224 private ServletFileUpload getServletFileUpload(){ 225 String fileMaxSize = FileUploadAppProperties.getInstance().getProperty("file.max.size"); 226 String totalFileMaxSize = FileUploadAppProperties.getInstance().getProperty("total.file.max.size"); 227 228 DiskFileItemFactory factory = new DiskFileItemFactory(); 229 230 factory.setSizeThreshold(1024 * 500); 231 File tempDirectory = new File(TEMP_DIR); 232 factory.setRepository(tempDirectory); 233 234 ServletFileUpload upload = new ServletFileUpload(factory); 235 236 upload.setSizeMax(Integer.parseInt(totalFileMaxSize)); 237 upload.setFileSizeMax(Integer.parseInt(fileMaxSize)); 238 239 return upload; 240 } 241 242 }
8)用于存储文件上传的单例工具类FileUploadAppProperties
1 package com.sunyard.utils; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 6 /** 7 * <p>上传下载参数单例类</p> 8 * @author:774346810@qq.com 9 * @date:2017-6-16 10 */ 11 public class FileUploadAppProperties { 12 13 private Map<String, String> properties = new HashMap<String, String>(); 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 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'upload.jsp' starting page</title> 13 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="This is my page"> 19 <!-- 20 <link rel="stylesheet" type="text/css" href="styles.css"> 21 --> 22 <script type="text/javascript" src="${pageContext.request.contextPath }/scripts/jquery-1.7.2.js"></script> 23 <script type="text/javascript"> 24 25 $(function(){ 26 27 var i = 2; 28 29 $("#addFile").click(function(){ 30 $(this).parent().parent().before("<tr class='file'><td>File" 31 + i + ":</td><td><input type='file' name='file" 32 + i + "'/></td></tr>" 33 + "<tr class='desc'><td>Desc" 34 + i + ":</td><td><input type='text' name='desc" 35 + i + "'/><button id='delete" 36 + i + "'>删除</button></td></tr>"); 37 i++; 38 39 //获取新添加的删除按钮 40 $("#delete" + (i-1)).click(function(){ 41 var $tr = $(this).parent().parent(); 42 $tr.prev("tr").remove(); 43 $tr.remove(); 44 45 //对 i 重写排序 46 $(".file").each(function(index){ 47 var n = index + 1; 48 49 $(this).find("td:first").text("File" + n); 50 $(this).find("td:last input").attr("name", "file" + n); 51 }); 52 53 $(".desc").each(function(index){ 54 var n = index + 1; 55 56 $(this).find("td:first").text("Desc" + n); 57 $(this).find("td:last input").attr("name", "desc" + n); 58 }); 59 60 i = i - 1; 61 }); 62 63 return false; 64 }); 65 66 }); 67 68 </script> 69 </head> 70 71 <body> 72 <font color="red">${message }</font> 73 <br><br> 74 75 76 <form action="upload" method="post" enctype="multipart/form-data"> 77 78 <table> 79 <tr class="file"> 80 <td>File1:</td> 81 <td><input type="file" name="file1"/></td> 82 </tr> 83 <tr class="desc"> 84 <td>Desc1:</td> 85 <td><input type="text" name="desc1"/></td> 86 </tr> 87 88 <tr> 89 <td><input type="submit" id="submit" value="提交"/></td> 90 <td><button id="addFile">新增一个附件</button></td> 91 </tr> 92 </table> 93 94 </form> 95 </body> 96 </html>
将项目部署服务器,启动,访问http://127.0.0.1:8080/fileupload/app/upload.jsp后出现下面的页面
点击上传,就可以完成文件上传的功能。
可以去服务器和数据库中查看是否上传成功,如下:
至此,文件上传功能完成。
***************************************************************
文件下载:
为了演示,我们将需要下载的文件内容写死,处理下载的servlet代码如下。
1 package com.sunyard.servlet; 2 3 import java.io.FileInputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.OutputStream; 7 import java.net.URLEncoder; 8 9 import javax.servlet.ServletException; 10 import javax.servlet.http.HttpServlet; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 14 import com.sunyard.db.UploadFileDao; 15 16 /** 17 * <p>下载servlet</p> 18 * @author:774346810@qq.com 19 * @date:2017-6-18 20 */ 21 public class DownLoadServlet extends HttpServlet{ 22 23 private static final long serialVersionUID = -1409324086440387753L; 24 25 @Override 26 protected void doGet(HttpServletRequest request, HttpServletResponse response) 27 throws ServletException, IOException { 28 response.setContentType("application/x-msdownload"); 29 30 String fileName = "文件下载.docx"; 31 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); 32 33 OutputStream out = response.getOutputStream(); 34 String pptFileName = "D:\\apache-tomcat-6.0.16\\webapps\\fileupload\\WEB-INF\\files\\149837444825180585.docx"; 35 36 InputStream in = new FileInputStream(pptFileName); 37 38 byte [] buffer = new byte[1024]; 39 int len = 0; 40 41 while((len = in.read(buffer)) != -1){ 42 out.write(buffer, 0, len); 43 } 44 45 in.close(); 46 } 47 48 }
同样,开启服务,打开浏览器访问
既可以得到需要你下载的文件。
至此,文件上传下载的小案例都在这里了。
参考文章:http://blog.ncmem.com/wordpress/2023/11/27/javaweb%e4%b9%8b%e6%96%87%e4%bb%b6%e7%9a%84%e4%b8%8a%e4%bc%a0%e4%b8%8b%e8%bd%bd/
欢迎入群一起讨论