Response下载文件

Posted woshi123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Response下载文件相关的知识,希望对你有一定的参考价值。

捣鼓了捣鼓了下载文件,虽然具体的响应头的知识和HttpServletResponse、ServletResponse的有些方法了解的还不够详细。。。。

package com.woshi.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/download")
public class DownLoadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String download = getServletContext().getRealPath("WEB-INF/downloads/download.jpg");
        String fileName = download.substring(download.lastIndexOf("\")+1);
        resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        FileInputStream inputStream = new FileInputStream(download);
        ServletOutputStream servletOutputStream = resp.getOutputStream();
        byte[] bbuf = new byte[1024];
        int hasRead = 0;
        while ((hasRead=inputStream.read(bbuf))>0){
            servletOutputStream.write(bbuf,0,hasRead);
        }
        inputStream.close();
        servletOutputStream.close();
    }
}

以上是关于Response下载文件的主要内容,如果未能解决你的问题,请参考以下文章

Docker删除报错:Error response from daemon: conflict: unable to delete 08b152afcfae (must be forced)(代码片段

生成和下载 excel 文件会生成 ERR_INVALID_RESPONSE

response的代码解析

response的代码解析

完全下载文件时,将下载的文件从一个片段传递到另一个片段

response-下载文件步骤