文件上传与下载可谓上网中的常见现象。apache为我们准备了用于文件上传与下载的两个jar包(commons-fileupload-1.2.1.jar,commons-io-1.4.jar)。我们在web项目中,将这两个jar包添加依赖,就可以使用客户端上传文件、服务器端下载文件的功能。
我们假设一个前端页面(如jsp页面)向服务器发起一个上传文件的请求,这时,表单必须必须用POST方式提交,设置表单提交格式为enctype=”multipart/form-data”,表示表单将能够提交字节数据,而不是键值对;服务器获取数据的时候,就不能request.getParameter了,必须用流获取;我们在服务器端用工具类库,对接收到的数据进行解析分析,及文件转储。
前端页面的表单如下:
<form action="UploadServlet" method="post" enctype="multipart/form-data"> <input type="text" name="in_data1"><%--提交普通键值对数据--%><br><br> <input type="file" name="uploadFile"><%--上传文件--%><br><br> <input type="submit" value="提交"> </form>
接下来是处理文件上传与下载的核心工具类:
import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; 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.util.Iterator; import java.util.List; /** * 处理文件上传与下载 */ @WebServlet(name = "UploadServlet",urlPatterns = "/UploadServlet") public class UploadServlet extends HttpServlet { private String dirPath=null; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //处理中文文件名乱码 request.setCharacterEncoding("UTF-8"); genUploadDir(request);//创建文件上传的根目录 // 检查前端发来的请求是否文件上传请求 boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { //符合文件上传的要求,则进行文件的解析和转储 // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request try { List<FileItem> items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { //如果是一个普通表单域 processFormField(item); } else { //如果是文件域 processUploadedFile(item); } } response.getWriter().write("successful"); } catch (FileUploadException e) { e.printStackTrace(); } } } //创建我们文件上传的根目录 private void genUploadDir(HttpServletRequest request) { if (dirPath==null) { dirPath =request.getServletContext().getRealPath("/WEB-INF/upload/"); File dir=new File(dirPath); //如果根目录不存在 if (!dir.exists()) { //则新建该文件夹 dir.mkdirs(); } } } private void processUploadedFile(FileItem item) { String fieldName = item.getFieldName(); System.out.println("fieldName = " + fieldName); String fileName = item.getName(); System.out.println("fileName = " + fileName); long sizeInBytes = item.getSize(); System.out.println("sizeInBytes = " + sizeInBytes); File uploadedFile = new File(dirPath,fileName); try { item.write(uploadedFile); } catch (Exception e) { e.printStackTrace(); } } private void processFormField(FileItem item) { String name = item.getFieldName(); System.out.println("name = " + name); String value = item.getString(); System.out.println("value = " + value); System.out.println("======================================"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }
在idea中运行tomcat服务器后,在前端表单中填入数据与上传的文件,服务器控制台显示文件上传成功:
键值对数据 name = in_data1 value = helloworld ====================================== 上传文件数据 fieldName = uploadFile fileName = JVM指令.txt sizeInBytes = 28733