Languages

Express.js - res.download() doesn't work with React.js

3 points
Asked by:
JoanneSenior
1070

I am trying to download .webm video file from server but res.download() method doesn't show any prompt, alert or errors.

My code looks like:

Backend:

const path = require('path');

// ...

app.get('/download/:id', (req, res) => {
    const videoId = req.params.id;
    res.download(path.resolve(`${__dirname}/path/to/${videoId}.webm`));
});

// ...

Frontend download method which I assign to onClick:

const downloadVideo = async (id) => {
    await axios
        .get('/download/' + id)
        .catch((error) => alert(error));
};
1 answer
3 points
Answered by:
JoanneSenior
1070

The problem is related with invoking the download prompt.

Quick solution:

  • create invisible a HTML element with download property/attribute,
  • set its href property to the '/download/' + id endpoint,
  • invoke click() method on the a element,
  • remember to remove a element.

Hint: remember to use res.download() with app.get(), other types may cause problems.

 

Practical example

Your frontend source code should look like this:

const downloadVideo = (id) => {
    const a = document.createElement('a');
    a.style = 'display: none';
    a.href = '/download/' + id;
    a.download = id + '.webm';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
};


// Usage example:

downloadVideo('my-video');  // it calls '/download/my-video' path

 

See also

  1. JavaScript - run file download (instead of opening)
  2. HTML - run file download on link click (instead of opening)

0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join