JavaWeb 之文件下载

1. 下载概述

  • 下载就是向客户端响应字节数据! 将一个文件变成字节数组, 使用 response.getOutputStream()
    来响应给浏览器!!

2. 下载要求

  1. 两个头一个流
    • Content-Type: 传递给客户端的文件的 MIME 类型;
      可以使用文件名称调用 ServletContext 的 getMimeType() 方法, 得到 MIME 类型!
    • Content-Disposition:attachment;filename=xxx:
      它的默认值为 inline, 表示在浏览器窗口中打开! attachment 表示附件, filname 后面跟随的是显示在
      下载框中的文件名称!
    • 流:要下载的文件数据!

3. 具体代码

    // 下载
    public class DownloadServlet extends HttpServlet{
        public void doGet(HttpServletRequest request, HttpServletResponse resp)
                throws ServletException,IOException{

            String filename = "F:浮夸.mp3";

            //根据文件名获取 MIME 类型
            String contentType = this.getServletContext().getMimeType(filename);

            String contentDisposition = "attachment;filename=a.mp3";

            // 输入流
            FileInputStream input = new FileInputStream(filename);

            // 设置头
            resp.setHeader("Content-Type",contentType);
            resp.setHeader("Content-Disposition",contentDisposition);

            // 获取绑定了客户端的流
            ServletOutputStream output = resp.getOutputStream();

            // 把输入流中的数据写入到输出流中
            IOUtils.copy(input,output);
            input.close();
        }
    }

4. 下载文件编码问题

  1. 显示在下载框中为中文名称时,会出现乱码
    • FireFox: Base64 编码;
    • 其他大部分浏览器: URL 编码.
  2. 通用方案: filename = new String(filename.getBytes("GBK"),"ISO-88859-1");

参考资料:

原文地址:https://www.cnblogs.com/linkworld/p/7636734.html