pdf文件通过IO流传给前端

public class pdfStream {
    // 使用文件流方式将PDF文件传递给前端可以通过以下步骤实现:
    //
    // 在后端,将PDF文件以流的形式读取并发送给前端。具体代码如下所示:
    @GetMapping("/download")
    public void downloadPdf(HttpServletResponse response) throws IOException {
        // 设置响应头,指定文件类型为PDF
        response.setContentType("application/pdf");

        // 读取PDF文件
        File file = new File("path/to/your/pdf/file.pdf");
        FileInputStream fileInputStream = new FileInputStream(file);

        // 获取输出流
        OutputStream outputStream = response.getOutputStream();

        // 将PDF文件流写入输出流
        byte[] buffer = new byte[1024];
        int length;
        while ((length = fileInputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }

        // 关闭流
        outputStream.flush();
        outputStream.close();
        fileInputStream.close();
    }
    
    // 前端通过Ajax请求该接口来接收文件流并进行处理。示例代码如下:
    // javascript
    // function downloadPdf() {
    //     var xhr = new XMLHttpRequest();
    //     xhr.open('GET', '/download', true);
    //     xhr.responseType = 'blob'; // 设置响应类型为Blob
    //
    //     xhr.onload = function(e) {
    //         if (this.status === 200) {
    //             var blob = new Blob([this.response], {type: 'application/pdf'});
    //             var link = document.createElement('a');
    //             link.href = window.URL.createObjectURL(blob);
    //             link.download = 'file.pdf';
    //             link.click();
    //         }
    //     };
    //
    //     xhr.send();
    // }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值