本文共 6414 字,大约阅读时间需要 21 分钟。
该功能需要添加三个jar,分别如下:
javax.servlet javax.servlet-api 3.0.1 commons-fileupload commons-fileupload 1.3.1 commons-io commons-io 2.4
<%@ page contentType="text/html;charset=UTF-8" language="java"%>${message}${fileName}<%--https://www.baidu.com/s?wd=nofollow%E6%A0%87%E7%AD%BE&tn=SE_PcZhidaonwhc_ngpagmjz&rsv_dl=gh_pc_zhidao--%><%--nofollow不要追踪此特定链接--%>file
action的内容为后端接收的地址,即为后端代码中@WebServlet("/fileUpload")的地址。
package com.hly.jsp.file;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileUploadException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;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 java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.List;/** * @author :hly * @github :github.com/SiriusHly * @blog :blog.csdn.net/Sirius_hly * @date :2018/8/20 */@WebServlet("/fileUpload")public class FileUpload extends HttpServlet { //临界值,超过临界值,上传过程中会存到临时目录 private static final int BOUNDARY_MEMORY_SIDE = 1024 * 1024 * 10; //文件最大值 private static final int MAX_MEMORY_SIDE = 1024 * 1024 * 300; //请求值 private static final int MAX_REQUEST_MEMORY_SIDE = 1024 * 1024 * 1000; public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { //判断普通表单还是文件上传表单,enctype属性是否是"multipart/form-data"。 if (!ServletFileUpload.isMultipartContent(request)) { System.out.println("不是多媒体上传"); PrintWriter out = response.getWriter(); out.println("不是多媒体上传"); out.flush(); return; } //配置上传参数 DiskFileItemFactory factory = new DiskFileItemFactory(); //设置临界值,超过部分存在临时目录 factory.setSizeThreshold(BOUNDARY_MEMORY_SIDE); //设置临时存储目录,上传过程中超过大小存到临时目录中,也可以设置成系统临时存储目录,https://www.cnblogs.com/nbjin/p/7392541.html File tempFile = new File("d:/FileUploadTemp"); if(!tempFile.exists()) tempFile.mkdirs(); factory.setRepository(tempFile); ServletFileUpload upload = new ServletFileUpload(factory); //编码 upload.setHeaderEncoding("UTF-8"); //设置文件最大上传值 upload.setFileSizeMax(MAX_MEMORY_SIDE); //设置文件最大请求值,包括所有form upload.setSizeMax(MAX_REQUEST_MEMORY_SIDE); //设置相对路径 String path = getServletContext().getRealPath("/") + File.separator + "uploadFile"; File uploadDir = new File(path); if (!uploadDir.exists()) { uploadDir.mkdirs(); } try { //解析请求内容获取文件数据 ListfileItems = upload.parseRequest(request); if (fileItems != null && fileItems.size() > 0) { for (FileItem item : fileItems) { //判断是否为普通类型,否则为file类型 if (!item.isFormField()) { //得到前端的name String fileName = item.getName(); String filePath = path + File.separator + fileName; File storeFile = new File(filePath); System.out.println("上传路径为:" + filePath); //保存文件到硬盘 item.write(storeFile); request.setAttribute("message", "上传成功"); request.setAttribute("fileName", fileName); // request.setAttribute(); } } }else{ request.setAttribute("message", "上传失败"); } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } getServletContext().getRequestDispatcher("/file/fileUpload.jsp").forward(request, response); System.out.println("上传成功"); }}
package com.hly.jsp.file;import javax.servlet.ServletContext;import javax.servlet.ServletOutputStream;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.*;/** * @author :hly * @github :github.com/SiriusHly * @blog :blog.csdn.net/Sirius_hly * @date :2018/8/22 */@WebServlet("/FileDownload")public class FileDownload extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String fileName = request.getParameter("fileName"); System.out.println("下载路径为:"+fileName); //设置mime类型,getMimeType获得文档类型,这里是text/plain response.setContentType(getServletContext().getMimeType(fileName)); System.out.println("mime类型:"+getServletContext().getMimeType(fileName)); //设置Context-Disposition //Content-disposition:HTTP相应头的属性,允许用户下载软件到磁盘 //attachment表示以附件方式下载。如果要在页面中打开,则改为inline。 response.setHeader("Content-Disposition", "attachment;filename=" + fileName); //输入流 String filePath = getServletContext().getRealPath("/")+ File.separator +"uploadFile"+File.separator +fileName; InputStream in = new FileInputStream(filePath); ServletOutputStream os = response.getOutputStream(); //缓冲区 int len =1; byte[] b = new byte[1024]; while ((len = in.read(b))!=-1){ os.write(b,0,len); } in.close(); os.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { doGet(request, response); }}
前端代码的文件目录为:
上传的文件可以在target里面找到
1.关于代码中的getName()方法
源码如下,我们可以发现他返回的是前端的name,当不是普通类型的表单,是file时,则进行保存
@Override public String toString() { return format("name=%s, StoreLocation=%s, size=%s bytes, isFormField=%s, FieldName=%s", getName(), getStoreLocation(), Long.valueOf(getSize()), Boolean.valueOf(isFormField()), getFieldName()); }