1

I've created an expressjs server to provide some audio files that I want to download from the frontend. The frontend is build using react.

GET requests to localhost:4000/download are handled this way:

app.get('/download', (req, res) => {
    const filename = req.query.filename;
    const pathToSharedDirectory = '';// build path
    return res.download(pathToSharedDirectory + '/' + filename, (err) => {
        // handle errors
    });
});

In the frontend I do the following:

export const DownloadFileOnButtonClick = async (file: any) => {
    axios.get('/download?filename=' + encodeURIComponent(file.filename), {
        baseURL: 'http://localhost:4000'
    })
        .then(r => {
            downloadFile(r.data, file.filename)
        })
        .catch(err => console.log(err));
}

const downloadFile = (data: unknown, fileName: string): void => {
    const a = document.createElement('a');
    document.body.appendChild(a);
    a.setAttribute('style', 'display: none');
    // Log size of the binary js string
    console.log((data as string).length)

    const blob = new Blob([data as string], { type: 'audio/mpeg' });
    const url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = `${fileName}`;
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
};

DownloadFileOnButtonClick is called, when a button is clicked.

Now the problem is, that the file that is downloaded has approximately twice the size of the original file and cannot be played by vlc.

The size of the original file is 6768429 bytes (output of ls -l).

The size of the received data string is 6768429 bytes.

The size of the generated blob is 11934675.

What do I have to do, to download audio files? Is there an easier way to do that?

Thanks in advance.

MrToast
  • 1,159
  • 13
  • 41

1 Answers1

2

I think you forgot the header responseType: 'arraybuffer' ? I tried and succeeded in downloading a fine Excel file. See this topic Download binary file with axios

Try this:

 axios.get('/download?filename=' + encodeURIComponent(file.filename), {
      responseType: 'arraybuffer',  
      baseURL: 'http://localhost:4000'
    })
gladix
  • 302
  • 2
  • 11