【问题标题】:Downloading a video from an API in React using Axios creates an empty mp4 file使用 Axios 从 React 中的 API 下载视频会创建一个空的 mp4 文件
【发布时间】:2021-09-26 17:18:21
【问题描述】:

我有一个返回视频的后端 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);
    });
};

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

【问题讨论】:

    标签: reactjs api video axios


    【解决方案1】:

    不知道这是否能解决问题,但您的请求配置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}'
        }
    };
    

    【讨论】:

    • 这是引导我走向正确道路的部分答案。谢谢你。在请求后附加此代码会导致运行代码const response = await axios(config); const blobData: Blob = response.data; //Create download link const blobURL = URL.createObjectURL(blobData); const link = document.createElement('a'); link.href = blobURL; link.download = ${UUID}.mp4; link.click(); 编辑:如何让代码在此处正确格式化?
    猜你喜欢
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 2015-11-20
    • 2017-06-20
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多