如何解决我在使用 ReactJS 从 Nodejs 下载文件时遇到问题
我在某个问题上需要一些帮助。我尝试从我的服务器 Nodejs 下载我的客户端 ReactJs 上的文件。 我已经进入我的 server.js :
router.route("/download/:filesaveas").get(function(req,res) {
const fileLocation = "public/files/" + req.params.filesaveas;
const file = req.params.filesaveas;
res.download(fileLocation,file,(err) => {
if (err) console.log(err);
});
当我尝试直接从服务器 http://localhost:4000/cww/download/testfile.pdf 下载时,下载成功,我没有任何错误,文件也没有损坏。
在我的客户端,我有一个函数 downloadFile,它由按钮“onclick”操作调用。
import download from 'downloadjs'
downloadFile = (filetodownload) => {
axios.get('http://localhost:4000/cww/download/'+filetodownload)
.then(res => {
var filename = "testfile.pdf"
download(res.data,scriptname,"text/plain");
});
}
当我点击按钮时。已下载某些内容,但文件似乎已损坏。无法打开...我想,服务器的响应数据有问题。 通过执行 console.log(res.data),我可以看到我的内容 PDF 的一部分,但有些奇怪 字符(如编码)但无法下载正确的文件。
感谢您的帮助。
解决方法
如果您想要最简单的选择,那就是打开一个包含该文件地址的新标签,该标签仅在路由是公开的情况下才有效。
const newTab = false;
window.open('http://localhost:4000/cww/download/testfile.pdf',newTab ? '' : '_self' );
但是您可以在不涉及文件编码的情况下完成此操作,甚至可以为此使用 axios:
onClick() {
const fileName = 'testfile.pdf';
fetch('http://localhost:4000/cww/download/testfile.pdf',{
method: 'GET',headers: {
'Content-Type': 'application/json'
// Security Headers if needed
},body: undefined,})
.then((data) => {
return data.blob();
})
.then((data) => {
if (data.size === 0) {
throw new Error('File not found');
}
const fileURL = URL.createObjectURL(data);
const downloadLink = document.createElement('a');
downloadLink.href = fileURL;
downloadLink.download = fileName;
downloadLink.click();
})
.catch((err) => {
console.log(err);
// Error Action
});
}
后端将简单地将文件流式传输给用户。
我对 res.download 了解不多(可能是更好的解决方案)
import * as fs from 'fs';
export async function getFile(request,response) {
const fileStream = fs.createReadStream('yourFileAddress',{});
fileStream.on('error',(err) => {
console.log(err.message);
response.status(404).send();
fileStream.removeAllListeners();
});
fileStream.on('end',() => {
console.log('Streamed successfully to user');
fileStream.removeAllListeners();
});
// finally starting the stream
fileStream.pipe(response);
}
,
感谢您的帮助!我刚刚发现了我的错误! 我忘了添加 ReponseType: blob 现在它完美运行 ;-)
downloadFile = (filetodownload) => {
axios.get('http://localhost:4000/cww/download/'+filetodownload,{responseType: 'blob'})
.then(res => {
var filename = "testfile.pdf"
download(res.data,scriptname,"text/plain");
});
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。