节点下载方法产生空文件 [英] Node download method produces empty file
问题描述
要练习我的节点,我正在尝试制作文件下载器。目的是从数据库(当前为mp3)获取文件的url,将其下载到项目中,并在客户端上用作href。
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.
我设法实现了诺言,并下载了文件,但是文件说它是空的,但是当我进入项目时,我可以打开文件( mp3)好。
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
});
});
})
按钮设置为(使用ejs):
And the button is set up as (using ejs):
<a href="/dist/<%= song_link %>" download>Download <%= name %></a>
有人能指出我正确的方向吗? console.logs都显示下载成功在呈现成功页面之前完成,因此我不确定为什么会显示失败-空文件。
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".
推荐答案
已修复:我认为问题在于,当我将项目设置为使用公共文件夹中的客户端资产时,我将文件保存到dist文件夹中。将文件保存到已解决问题的 / public / assets:
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");
这篇关于节点下载方法产生空文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!