Skip to content Skip to sidebar Skip to footer

Failed To Download An Image File From My Node Js Server Through My Frontend (my Backend And Frontend Are Decoupled)

My nodejs backend is running on localhost:8080 and frontend on localhost:8081 using http-server, I am not able to download file from my server side to client side, I am new to node

Solution 1:

Is that all of your servercode handling the download? If yes, you are not waiting for the readStream to properly open. And you should also add proper error handling, when the readStream couldn't be opened. Use

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

And to download a file with fetch(in my understanding this means saving the file to disk instead of displaying it in the browser) you nonetheless need to apply the means of the referenced question ...


Solution 2:

Try this one

Server

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

Client

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();
  })

Post a Comment for "Failed To Download An Image File From My Node Js Server Through My Frontend (my Backend And Frontend Are Decoupled)"