html 中使用 a 标签的 href 属性链接到资源路径和 url-pattern 再加上? key=value
- <h1>
- 打开文件, href 传输的路径是直接写资源路径的文件路径即可
- </h1>
- <a href="/s5/downloadResource/wolf.jpg">
- 点击会直接打开图片
- </a>
- <a href="/s5/downloadResource/a.txt">
- 直接打开文本文件
- </a>
- <hr/>
- <h1>
- 下载文件, href 传输的路径是 Servlet 资源路径加? 加 key 和 value
- </h1>
- <a href="/s5/download?filename=wolf.jpg">
- 下载图片
- </a>
- <a href="/s5/download?filename=a.txt">
- 下载文本
- </a>
服务端 Servlet: 文件下载案例的分析:
获取请求参数, getParameter() 根据参数名获取参数值
获取 getServletContext 对象, 用 getServletContext 对象的 getRealpath() 找到真实路径, 再用字节输入流输入到内存
设置响应头的 content-type 为 filename(filename 是什么类型需要 getMimeType 去获取)
设置响应头的 content-disposition 为 attachment 附件打开
- @webServlet("/download")
- public class DownloadServletTest extends HttpServlet {
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- // 1. 获取请求参数, 文件名称
- String filename = request.getParameter("filename");
- // 2. 找到真实路径, 使用字节输入流输入到内存
- ServletContext servletContext = request.getServletContext();
- String realPath = servletContext.getRealPath("/downlaodResource/" + filename); //+ filename 动态的获取文件名, 实现点拿个下载哪个
- FileInputStream fis = new FileInputStream(realPath);
- // 3. 设置响应头的 content-type 为 filename(filename 是什么类型需要 getMimeType 去获取)
- String mime = servletContext.getMimeType(filename);
- response.setHeader("content-type","mime");
- // 4. 设置响应头的 content-disposition 为 attachment 附件打开
- response.setHeader("content-disposition","attachment;filename"+filename);
- // 5. 将输入流的数据写出到输出流中, 完成对拷
- ServletOutputStream os = response.getOutputStream();
- byte[] buff = new byte[1024];
- int len = 0;
- while ((len = fis.read(buff)) != -1) {
- os.write(buff,0,len);
- }
- fis.close();
- }
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- this.doPost(request,response);
- }
- }
来源: http://www.bubuko.com/infodetail-3822297.html