今天简单学习一下在javaWeb中文件的上传与下载
首先,我们需要在项目中添加所需要的jar包
分别是 commons-fileupload-1.3.3.jar 和 commons-io-2.4.jar
https://files.cnblogs.com/files/aierben/%E5%B8%B8%E7%94%A8jar%E5%8C%85.zip
然后新建一个jsp文件,作为前台的访问页面,其内容如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="UpTest" method="post" enctype="multipart/form-data"> 上传文件:<input type="file" name="Upfile"/> <input type="submit" values="注册"/> </form> <a href="Download?filename=abc.png">下载</a> </body> </html>
然后我们上传对应的UpTest,代码如下:
package UpTestPack; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; 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 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; @WebServlet("/UpTest") public class UpTest extends HttpServlet { private static final long serialVersionUID = 1L; public UpTest() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=UTF-8"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(isMultipart) { //构造文件项工厂对象,可以理解为文件上传过程中所需环境,例如大小超过缓存区需要分配临时目录 FileItemFactory item = new DiskFileItemFactory(); //文件上传核心操作类 ServletFileUpload upload = new ServletFileUpload(item); try { //限制上传文件大小 upload.setFileSizeMax(15240); //获取前台传入值 List<FileItem> items = upload.parseRequest(request); //遍历前台数据 Iterator<FileItem> itemr = items.iterator(); String name = ""; int age = -1; while(itemr.hasNext()) { FileItem it = itemr.next(); //获取name 属性值 String FileName = it.getFieldName(); //如果是普通表单字段 直接取值 if(it.isFormField()) { //检验表单name字段 if(FileName == "Uname") { name = it.getString("utf-8"); }else if(FileName == "Uage") { age = Integer.parseInt(it.getString("utf-8")); } }else { //获取上传文件的文件名 String filename = it.getName(); //服务器存放路径 String path = request.getSession().getServletContext().getRealPath("UpTest"); File file = new File(path,filename); //上传到服务器 it.write(file); System.out.println(filename+"上传成功了"); } } } catch (FileUploadException e) { // TODO Auto-generated catch block System.out.println("文件大小超出限制"); //The field Upfile exceeds its maximum permitted size of 15240 bytes e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
文件下载-下载相对于上传来说就要简单许多
1. 首先在服务器指定文件路径
2.设置响应头信息
3.写回到客户端
代码如下:
package UpTestPack; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/Download") public class Download extends HttpServlet { private static final long serialVersionUID = 1L; public Download() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String filename = request.getParameter("filename"); //响应头类型 response.addHeader("content-type", "application/octet-stream"); response.addHeader("content-Disposition", " attachment; filename="+filename); //下载文件流 InputStream in = getServletContext().getResourceAsStream("res/abc.png"); byte[] bytes = new byte[1024]; OutputStream out = response.getOutputStream(); int len = -1; while((len=in.read(bytes))!=-1) { out.write(bytes, 0, len); } out.close(); in.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }