后端间接向前端返回一个文件,浏览器自动识别实现下载性能

  1. 次要写一个办法,前端传来response,将数据写入response,不须要返回数据
  2. 要害就是在HTTP响应中设置:
    Content-Disposition
    Content-Type
  • Content-Disposition头用于批示浏览器如何解决响应的内容。将其设置为"attachment; filename=filename.extension"将通知浏览器以附件的模式下载文件,并将文件保留为指定的文件名。例如,如果您要下载名为example.pdf的文件,Content-Disposition头应该如下所示:

    Content-Disposition: attachment; filename=example.pdf
  • Content-Type头用于批示响应的内容类型。对于大多数文件,您能够应用"application/octet-stream"。例如,如果您要下载一个PDF文件,Content-Type头应该如下所示:

    Content-Type: application/octet-stream

    一旦您的后端返回此响应,浏览器将自动弹出下载对话框,容许用户将文件保留到他们的计算机上。

代码

private void download(String path, HttpServletResponse response) {        try {            // path是指想要下载的文件的门路            File file = new File(path);            System.out.println("文件门路: "+file.getPath());            // 获取文件名            String filename = file.getName();            System.out.println("文件名: "+filename);            // 获取文件后缀名            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();            System.out.println("文件后缀名:" + ext);            // 将文件写入输出流            FileInputStream fileInputStream = new FileInputStream(file);            InputStream fis = new BufferedInputStream(fileInputStream);            byte[] buffer = new byte[fis.available()];            fis.read(buffer);            fis.close();            // 清空response            response.reset();            // 设置response的Header            response.setCharacterEncoding("UTF-8");            //Content-Disposition的作用:告知浏览器以何种形式显示响应返回的文件,用浏览器关上还是以附件的模式下载到本地保留            //attachment示意以附件形式下载 inline示意在线关上 "Content-Disposition: inline; filename=文件名.mp3"            // filename示意文件的默认名称,因为网络传输只反对URL编码的相干领取,因而须要将文件名URL编码后进行传输,前端收到后须要反编码能力获取到真正的名称            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));// 告知浏览器文件的大小            response.addHeader("Content-Length", "" + file.length());            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());            response.setContentType("application/octet-stream");            outputStream.write(buffer);            outputStream.flush();        } catch (IOException ex) {            ex.printStackTrace();        }    }