微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法通过我的前端从我的 node js 服务器下载图像文件我的后端和前端是解耦的

如何解决无法通过我的前端从我的 node js 服务器下载图像文件我的后端和前端是解耦的

我的 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);
  })

前端响应:- 我收到了服务器的成功响应,但没有下载文件

enter image description here

请帮我解决这个问题

解决方法

这是您处理下载的所有服务器代码吗?如果是,则您不是在等待 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();
  })

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。