首页 > 解决方案 > 如何使用 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 从客户端消费流呢?或者也许有更好的解决方案?

标签: javascriptspring-bootvue.jsaxiosstreaming

解决方案


正如schnaidar所指出的,目前,Axios 无法使用来自客户端的流(问题 479)。

因此,解决方案是改用fetchAPI。但是,这是一项实验性功能,并不与所有浏览器兼容。根据我的测试,它在 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当前浏览器是否可用。如果没有,则将WritableStreamfromponyfill直接分配给streamSaver.WritableStream属性。

在 Google Chrome 78、Firefox 70、Safari 13 上测试;web-streams-polyfill 2.0.5StreamSaver.js 2.0.3


推荐阅读