response返回文件给前端

发布时间 2023-05-22 20:07:41作者: 黄大虾
    @GetMapping("/getPdf2")
    public void getPdf2(HttpServletResponse response) throws IOException {
        File file = new File("D://aasd.pdf");
        FileInputStream fileInputStream = new FileInputStream(file);
        ServletOutputStream outputStream = response.getOutputStream();

        String fileName = new String("我是PDF.pdf".getBytes(), StandardCharsets.ISO_8859_1);
        response.addHeader("Content-Disposition", "filename=" + fileName);
//        response.setContentType("application/pdf"); //该响应头在浏览器可能会直接预览
        response.setContentType("application/octet-stream");//改成这个,则弹出下载提示,而不是直接预览

        IOUtils.copy(fileInputStream,outputStream);
        fileInputStream.close();
        outputStream.close();
    }