JAVAWeb file download function

Personal blog address https://nfreak-man.cn

  1. Write html page, edit the href attribute of the hyperlink, point to the Servlet and pass the file name and format to be downloaded

  2. Servlet: * Get file name

    * Use the byte input stream to load files into memory

    * Specify the response header of response: content-disposition: attachmement; filename = xxx

    * Write data to the response output stream

html a tag format

href="/day15/downloadServlet?filename=鬼刀.png"

Servlet

@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求参数,文件名称
        String filename = request.getParameter("filename");
        //使用字节输入流加载文件进内存
        //找到文件的服务器路径
        ServletContext servletContext = this.getServletContext();
        String realPath = servletContext.getRealPath("/img/" + filename);
        //用字节流关联
        FileInputStream fis = new FileInputStream(realPath);

        //设置response的响应头
        //设置响应头类型:content-type
        String mimeType = servletContext.getMimeType(filename);
        response.setHeader("content-type",mimeType);
        //设置响应头打开方式:content-disposition
        //解决中文文件名问题
        //获取user-agent请求头
        String agent = request.getHeader("user-agent");
        //使用工具类方法编码文件名即可
        String fileName = DownLoadUtils.getFileName(agent, filename);
        response.setHeader("content-disposition","attachment;filename="+fileName);

        //将输入流的数据写出到输出流中
        ServletOutputStream sos = response.getOutputStream();
        byte[] buff = new byte[1024 * 8];
        int len = 0;
        while ((len = fis.read(buff))!=-1){
            sos.write(buff,0,len);
        }
        fis.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

Note: To solve the problem that the download of the Chinese file name cannot be displayed normally, you need to use the DownLoadUtils class to obtain the browser encoding method. Baidu search and download.

Published 28 original articles · praised 0 · visits 722

Guess you like

Origin blog.csdn.net/William_GJIN/article/details/104867310