[英]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.这是 React 前端的 GET 请求。 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.
我尝试添加 link.target = '_blank' 但这不起作用,它只是定期下载文件。
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这是 GET 请求的服务器端路由代码
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.