使用 Axios 从 React 中的 API 下载视频会创建一个空的 mp4 文件

问题描述

我有一个返回视频的后端 api(在 Postman 中验证路由)但是当尝试实现“下载视频”按钮时,它下载了一个文件

我已经尝试了多种实现,但结果最好是相同的,但这是当前的代码

const handleDownloadVideo = async () => {
    const axios = require('axios');

    const config = {
        method: 'get',url: `http://localhost:3001/api/v1/render/video/${UUID}/download/`,headers: { 
            'Authorization': 'Bearer {token}','responseType': 'blob','maxContentLength': Infinity,'maxBodyLength': Infinity
        }
    };

    axios(config)
    .then((response) => {
        const link = document.createElement('a');
        link.target = '_blank';
        link.download = `${UUID}.mp4`;
        link.href = URL.createObjectURL(new Blob([response.data],{ type: "video/mp4" }));
        link.click();
    })
    .catch(function (error) {
        console.error(error);
    });
};

我不认为这是一项艰巨的任务,但我已经为此苦苦挣扎了好几天。有人能解释一下我在这里做错了什么吗?

解决方法

不知道这是否可以解决问题,但您的请求配置 responseTypemaxContentLengthmaxBodyLength 应该在标头对象之外。

const config = {
    method: 'get',url: `http://localhost:3001/api/v1/render/video/${UUID}/download/`,responseType: 'blob',maxContentLength: Infinity,maxBodyLength: Infinity
    headers: {
        'Authorization': 'Bearer {token}'
    }
};