问题描述
我的 nodejs 后端在 localhost:8080 上运行,前端在 localhost:8081 上运行,使用 http-server,我无法从服务器端下载文件到客户端,我是 node js 的新手,所以面临一些问题
我尝试了什么
我在服务器端为我所需的文件创建了一个读取流,然后将其通过管道传输到 res 对象,我还设置了一些标题:-
res.setHeader("Content-Type","image/png") // as I am trying to download a
res.setHeader("Content-disposition",`inline; filename=${filename}`);
但是还是不行
代码:-
let filename = "hello.png";
let readStream = fs.createReadStream(path.join(__dirname,"..",chatDoc.chatContent));
res.setHeader("Content-Type","image/png")
res.setHeader("Content-disposition",`inline; filename=${filename}`);
readStream.pipe(res);
cors 代码:-
const cors = require("cors");
app.use(cors({
origin: "http://localhost:8081",credentials: true,withCredentials: true
}))
前端代码:-
fetch("http://localhost:8080/downloadNow",{
method:"POST",headers:{
"Content-Type":"application/json"
},body:JSON.stringify({
chatId:chatId
}),credentials:"include"
})
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log(err);
})
前端响应:- 我收到了服务器的成功响应,但没有下载文件。
请帮我解决这个问题
解决方法
这是您处理下载的所有服务器代码吗?如果是,则您不是在等待 readStream
正确打开。当无法打开 readStream 时,您还应该添加适当的错误处理。使用
let readStream = fs.createReadStream(path.join(__dirname,"..",chatDoc.chatContent));
readStream.on("open",() => {
res.setHeader("Content-Type","image/png")
res.setHeader("Content-Disposition",`inline; filename=${filename}`);
readStream.pipe(res);
})
readStream.on("error",e => {
console.log(e);
res.writeHead(400);
});
并且要使用 fetch
下载文件(在我看来,这意味着将文件保存到磁盘而不是在浏览器中显示),您仍然需要应用 referenced question ...
试试这个
服务器
let mime = {
html: 'text/html',txt: 'text/plain',css: 'text/css',gif: 'image/gif',jpg: 'image/jpeg',png: 'image/png',svg: 'image/svg+xml',js: 'application/javascript'
};
app.post('/imageDownload',async(req,res) => {
var type = mime[path.extname(req.body.imagePath).slice(1)] ||
'text/plain';
var s = fs.createReadStream(file);
s.on('open',function () {
res.set('Content-Type',type);
s.pipe(res);
});
s.on('error',function (err) {
console.log(err)
res.send(err)
});
}
客户端
fetch(`/imageDownload`,{
method: 'POST',headers:{
"Content-Type":"application/json"
},body:JSON.stringify({
imagePath:url
}),}).then(response => response.blob())
.then(function(myBlob) {
const url = window.URL.createObjectURL(new Blob([myBlob]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download',"filename.jpg");
document.body.appendChild(link);
link.click();
})