通过我的前端从我的节点js服务器下载图片文件失败(我的后端和前端是解耦的)

人气:292 发布:2022-10-16 标签: javascript node.js express pipe response

问题描述

我的NodeJS后端运行在localhost:8080上,前端运行在localhost:8081上,使用的是http-server,我无法将文件从服务器端下载到客户端,我对节点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.

的方法

359