SpringBoot强制下载文件

SpringBoot强制下载文件

关键代码

 

    File pdfFile=new File(文件路径);
    response.setContentType("application/force-download");
    response.setHeader("Content-Disposition", "attachment;fileName=" + pdfFile.getName());
    response.setContentLengthLong(pdfFile.length());
    response.setHeader("Access-Control-Expose-Headers", "FileName");

    byte[] buffer = new byte[1024];
    FileInputStream fis = null; //文件输入流
    BufferedInputStream bis = null;

    OutputStream os = null; //输出流
    try {
        os = response.getOutputStream();
        fis = new FileInputStream(pdfFile);
        bis = new BufferedInputStream(fis);
        int i = bis.read(buffer);
        while (i != -1) {
            os.write(buffer);
            i = bis.read(buffer);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    try {
        bis.close();
        fis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

你可能感兴趣的:(文件下载)