EN
Express.js - res.download() doesn't work with React.js
1
answers
3
points
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
The problem is related with invoking the download prompt.
Quick solution:
- create invisible
a
HTML element withdownload
property/attribute, - set its
href
property to the'/download/' + id
endpoint, - invoke
click()
method on thea
element, - remember to remove
a
element.
Hint: remember to use
res.download()
withapp.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
0 comments
Add comment