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();
// }
}
pdf文件通过IO流传给前端
最新推荐文章于 2025-04-01 13:22:45 发布