javascript - 如何使用 StreamSaver.js 从 Axios 消费下载流?
问题描述
在我使用 Spring Boot 框架构建的服务器端,它返回一个如下所示的流:
public ResponseEntity<StreamingResponseBody> downloadFiles(@RequestBody DownloadRequest payload) {
// Set proper header
String contentDisposition = "attachment;filename=download.zip";
// Build the response stream
StreamingResponseBody stream = outputStream -> {
archiveManagerService.downloadFiles(payload.getArchiveId(), payload.getFiles(), outputStream);
};
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType("application/zip"))
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
.body(stream);
}
这对我来说可以。我可以使用 Postman 下载文件。现在,我需要使用Axios从客户端调用此端点。经过一番搜索,我找到了一个名为StreamSaver.js的库。这个库可以很好地与fetch配合使用(查看源代码以查看示例代码)。但是,我不知道如何将它与 Axios 一起使用。
目前,我的代码如下所示(我使用 Vuejs):
import axios from 'axios';
import streamSaver from 'streamsaver';
const instance = axios.create({
baseURL: '<my_base_url>',
headers: {
'Content-Type': 'application/json'
}
});
instance.post('/download', postData, {
responseType: 'stream'
})
.then(response => {
// What should I put here? These lines below don't work
const fileStream = streamSaver.createWriteStream('download.zip');
response.data.pipe(fileStream);
});
我有一个错误说
response.data.pipe 不是函数
那么,如何使用 Axios 从客户端消费流呢?或者也许有更好的解决方案?
解决方案
正如schnaidar所指出的,目前,Axios 无法使用来自客户端的流(问题 479)。
因此,解决方案是改用fetch
API。但是,这是一项实验性功能,并不与所有浏览器兼容。根据我的测试,它在 Google Chrome 上运行良好,但不适用于 Firefox 或 Safari。为了克服这个问题,我使用了另一个名为web-streams-polyfill
.
以下是我的代码(仅包括重要部分):
import { WritableStream } from 'web-streams-polyfill/ponyfill';
import streamSaver from 'streamsaver';
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => {
let contentDisposition = response.headers.get('Content-Disposition');
let fileName = contentDisposition.substring(contentDisposition.lastIndexOf('=') + 1);
// These code section is adapted from an example of the StreamSaver.js
// https://jimmywarting.github.io/StreamSaver.js/examples/fetch.html
// If the WritableStream is not available (Firefox, Safari), take it from the ponyfill
if (!window.WritableStream) {
streamSaver.WritableStream = WritableStream;
window.WritableStream = WritableStream;
}
const fileStream = streamSaver.createWriteStream(fileName);
const readableStream = response.body;
// More optimized
if (readableStream.pipeTo) {
return readableStream.pipeTo(fileStream);
}
window.writer = fileStream.getWriter();
const reader = response.body.getReader();
const pump = () => reader.read()
.then(res => res.done
? writer.close()
: writer.write(res.value).then(pump));
pump();
})
.catch(error => {
console.log(error);
});;
这个想法是检查window.WritableStream
当前浏览器是否可用。如果没有,则将WritableStream
fromponyfill
直接分配给streamSaver.WritableStream
属性。
在 Google Chrome 78、Firefox 70、Safari 13 上测试;web-streams-polyfill 2.0.5和StreamSaver.js 2.0.3
推荐阅读
- java - 如何检查隐藏元素是否显示在硒中
- maven - 无法在 SonarQube 中验证 mule 应用程序的 pom.xml
- javascript - 粘性导航栏不隐藏可滚动元素
- docker - Docker contianer 限制 CPU 资源
- sql - DISTINCT 没有给出预期的结果
- python - 创建python软链接失败
- android - 如何使用 MutableStateFlow 在 android 中保存缓存?
- javascript - 按比例裁剪图像
- java - 如何从 Solace JMS 队列接收 JSON 消息,队列已创建
- python - 使用 OpenCV 处理透明背景