问题
To practice my node I am trying to make a file downloader. The aim is to get a url of a file from a database (currently mp3), download it to the project and use it as an href on the client side.
I have managed to get the promises working and a file downloads, however the file is saying it's empty, but when I go into the project, I can open the file(mp3) fine.
Here is what I have so far:
.then(() => {
Promise.resolve()
.then(() => {
return new Promise(resolve => {
console.log("Started download");
// req.body.total_source is the full url of the file
console.log(req.body.total_source);
setTimeout(() => {
download(req.body.total_source, "dist").then(() => {
console.log("downloaded!");
resolve();
});
}, 1000);
});
})
.then(() => {
console.log("success page rendered");
res.render("success", {
// only get file name from url
song_link: req.body.total_source.substring(
req.body.total_source.lastIndexOf("/") + 1,
req.body.total_source.length
),
song_source: req.body.total_source,
name: req.body.name
});
});
})
And the button is set up as (using ejs):
<a href="/dist/<%= song_link %>" download>Download <%= name %></a>
Can anyone point me in the right direction? The console.logs all show that the download is finished before the success page is rendered, so i'm not sure why it says "Failed - empty file".
回答1:
FIXED: I think the problem was that I was saving the file to the dist folder, when I had setup the project to use client assets from a 'public' folder. Saving the files to "/public/assets" fixed to problem:
download(req.body.total_source, "public/assets");
来源:https://stackoverflow.com/questions/54982960/node-download-method-produces-empty-file