Downloading a video from an API in React using Axios creates an empty mp4 file

Viewed 803

I have a backend api that returns a video (verified route in Postman) but when trying to implement a "download video" button, it downloads an empty file

I've tried multiple implementations with at best identical results but here is the current code:

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);
    });
};

I wouldn't expect this to be a difficult task and yet have been struggling with it for multiple days now. Can anybody explain what I'm doing wrong here?

1 Answers

Don't know if this might solve the problem, but your request config responseType, maxContentLength and maxBodyLength should be outside the header object.

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