1.首页jsp 应该获取servlet请求转发过来的文件目录,显示文件名称, 注意:首先要进行逻辑判断,把list为空的情况筛选出来; 2.把转发来的list集合 展现在index页面中,在下载的超链接路径的参数传递文件名称,传到download的Servlet路径,然后在download的servlet的方法里面根据传来的名字,在资源目录里面找,如果存在该文件,则创建一个该文件的输入流进入内存,再通过response获得输出流,将输入流传到index页面 注意: 2.1应该设置传递的文件mime类型,resp.setContentType(contentType),通过逻辑判断file的文件类型2.2如果浏览器获取到该流后,应该设置浏览器的打开方式,比如直接下载,就要设置http头信息,如果文件名称包含中文,就会报错,解决方法是:将文件名进行URL编码 String encodedFileName = URLEncoder.encode(submittedFileName, "UTF-8"); resp.setHeader("Content-Disposition","attachment;filename="+encodedFileName); 2.3 输出流最后应该flush ,输入流close关闭
3.文件上传 需要在表单里action里写上upload的servlet路径,然后在servlet里面接收传来的文件需要使用post请求,注意需要在servlet设置@MultipartConfig,
注意:先设置编码方式 再获取打印流
resp.setContentType("text/html;charset=UTF-8"); PrintWriter writer = resp.getWriter();
4.servlet继承HttpServlet()
import javax.servlet.http.HttpServlet;
前端页面的代码 <%@ page import="cn.hutool.core.util.ArrayUtil" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <title>文件上传下载</title> </head> <body> <h1>文件列表</h1> <% String[] list = (String[]) request.getAttribute("list"); %> <% if (ArrayUtil.isNotEmpty(list)){ for (int i = 0; i<list.length; i++) { %> <a ><%=list[i]%></a> <a href="/download?name=<%=list[i]%>">下载</a> </br> <% } } %> <hr> <h2>文件上传</h2> <form action="upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <button>上传</button> </form> </body> </html>
index的Servlet
package fileupdown; 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.net.URLEncoder; @WebServlet("/index") public class Index extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // super.service(req, resp); //创建File对象,指向文件上传的目录 File file = new File("D:\\CodeAll\\code\\FirstWeb\\src\\main\\webapp\\resourse"); //获取该目录下的文件列表 String[] list = file.list(); req.setAttribute("list", list); req.getRequestDispatcher("index.jsp").forward(req, resp); } }
upload的servlet
package fileupdown; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import java.io.*; @WebServlet("/upload") @MultipartConfig public class FileUpload extends HttpServlet { @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 获取文件部分 Part part = req.getPart("file"); //获取上传的文件名 String submittedFileName = part.getSubmittedFileName(); // 获取文件内容流 InputStream fileContent = part.getInputStream(); OutputStream outputStream = new FileOutputStream("D:\\CodeAll\\code\\FirstWeb\\src\\main\\webapp\\resourse\\"+submittedFileName); byte[] bytes = new byte[1024]; int len = 0; while (-1!= (len =fileContent.read(bytes) )){ outputStream.write(bytes,0,len); } resp.setContentType("text/html;charset=UTF-8"); PrintWriter writer = resp.getWriter(); writer.print("<html>"); writer.print("<body>"); writer.print("<h2>文件上传成功!<h2>"); writer.print("<h2>3s后返回下载列表<h2>"); writer.print("</body>"); writer.print("</html>"); System.out.println("打印上传成功"); // resp.setHeader("Refresh", "3; url=index.jsp"); resp.setHeader("Refresh", "3; url=./index"); // resp.sendRedirect("/index"); } }
download的servlet
package fileupdown; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import java.io.*; import java.net.URLEncoder; @WebServlet("/download") @MultipartConfig public class FileDownload extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // super.service(req, resp); //获取上传到服务器的文件名 String submittedFileName = req.getParameter("name"); File file = new File("D:\\CodeAll\\code\\FirstWeb\\src\\main\\webapp\\resourse\\" + submittedFileName); if (file.exists()){ FileInputStream fileInputStream = new FileInputStream(file); String contentType = ""; if (file.getName().endsWith(".jpg") || file.getName().endsWith(".jpeg")) { contentType = "image/jpeg"; } else if (file.getName().endsWith(".png")) { contentType = "image/png"; } else if (file.getName().endsWith(".gif")) { contentType = "image/gif"; } else if (file.getName().endsWith(".pdf")) { contentType = "application/pdf"; } else if (file.getName().endsWith(".doc") || file.getName().endsWith(".docx")) { contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; } else if (file.getName().endsWith(".xls") || file.getName().endsWith(".xlsx")) { contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; } else if (file.getName().endsWith(".zip")) { contentType = "application/zip"; } else if (file.getName().endsWith(".txt")) { contentType = "text/html;charset=UTF-8"; } else if (file.getName().endsWith(".doc") || file.getName().endsWith(".docx")) { contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; } resp.setContentType(contentType); // 对文件名进行URL编码 String encodedFileName = URLEncoder.encode(submittedFileName, "UTF-8"); resp.setHeader("Content-Disposition", "attachment; filename="+encodedFileName); ServletOutputStream outputStream = resp.getOutputStream(); byte[] bytes = new byte[1024]; int len = 0; while (-1!=(len=fileInputStream.read(bytes))){ outputStream.write(bytes,0,len); } outputStream.flush(); fileInputStream.close(); }else { //进行文件不存在的处理 } } }