0%
前言
Javaweb实现文件下载
前端页面代码
- 在
/WebContent
目录下新建download.html
1 2 3 4 5 6 7 8 9 10 11
| <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1 align="center">文件下载</h1><br> <a href="download">下载</a> </body> </html>
|
Servlet代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| package io.github.feiju12138;
import java.io.FileInputStream; import java.io.IOException; import java.net.URLEncoder;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends HttpServlet { private static final long serialVersionUID = 1L;
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String path = getServletContext().getRealPath("/file"); String fileName = "1.jpg"; path += "/" + fileName;
resp.setHeader("content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf-8"));
FileInputStream fis = null; try { fis = new FileInputStream(path); byte buf[] = new byte[1024]; int len = 0; while((len = fis.read(buf)) > 0) { resp.getOutputStream().write(buf, 0, len); } } catch (Exception e) { } finally { if(fis != null) { fis.close(); } }
}
}
|
完成
参考文献
达内教育