简体   繁体   中英

How to open a PDF download into a new tab when calling a GET function from React frontend?

This is the GET request in the React frontend. Currently it starts the download and works fine, but I actually want it to open in a new tab and then download the file. I tried adding link.target = '_blank' but that did not work, it just downloaded the file regularly.

download2016(){
    var headers = new Headers();
    headers.append('Content-Type','application/pdf')
    fetch("http://localhost:5000/download/report/2016", {
      method: "get",
      headers: headers,
    }).then((response) => response.blob())
    .then((blob) => {
      const url = window.URL.createObjectURL(
        new Blob([blob]),
      );
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute(
        'download',
        'Mypdfname.pdf'
      );
      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
    });
  }

This is the server side route code for the GET request

const router = require('express').Router();
const fs = require('fs');
const path = require('path');

router.get('/report/2016',function(req, res){
    var tempfile = __dirname +  '\\mypdfname.pdf';
    console.log(tempfile);
    fs.readFile(tempfile,function (err,data){
        res.contentType("application/pdf");
        res.send(data);
        console.log("Visitor downloading 2016 file");
    });
});
module.exports = router;

Any help would be appreciated. Have a nice day

Instead of sending buffer to the front end try this.

Front end -

download2016(){
   window.open("http://localhost:5000/download/report/2016")
}

Backend Code -

const router = require('express').Router();
const fs = require('fs');
const path = require('path');

router.get('/report/2016',function(req, res){
   var tempfile = __dirname +  '\\mypdfname.pdf';
   res.download(tempfile, function(err) {
         if(err) {
             console.log('Something went wrong : ', err)
         } else {
             console.log('File downloaded.') 
         }
   });
});
module.exports = router;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM