在实现文件下载时,我们需要在响应头中添加附加信息
    response.addHeader(“Content-Disposition”, “attachment; filename=”+文件名);
    Content-Disposition:attachment
    该附加信息表示作为对下载文件的一个标识字段。不会在浏览器中显示而是直接做下载处理。
    filename=文件名
    表示指定下载文件的文件名

    1. import javax.servlet.ServletException;
    2. import javax.servlet.http.HttpServlet;
    3. import javax.servlet.http.HttpServletRequest;
    4. import javax.servlet.http.HttpServletResponse;
    5. import java.io.*;
    6. public class FileDownLoadServlet extends HttpServlet {
    7. @Override
    8. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    9. this.doPost(req, resp);
    10. }
    11. @Override
    12. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    13. //读取下载文件
    14. File file = new File("D:\\DownloadFile/rog.jpg");
    15. InputStream inputStream = new FileInputStream(file);
    16. byte[] buff = new byte[inputStream.available()];
    17. inputStream.read(buff);
    18. //在响应中添加附加信息
    19. resp.addHeader("Content-Disposition","attachment;filename="+file.getName());
    20. //产生响应
    21. OutputStream outputStream = resp.getOutputStream();
    22. outputStream.write(buff);
    23. outputStream.flush();
    24. outputStream.close();
    25. inputStream.close();
    26. }
    27. }

    image.png