[英]How to open a PDF download into a new tab when calling a GET function from React frontend?
這是 React 前端的 GET 請求。 目前它開始下載並且工作正常,但我實際上希望它在新選項卡中打開然后下載文件。 我嘗試添加 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);
});
}
這是 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;
任何幫助,將不勝感激。 祝你今天過得愉快
而不是發送緩沖區到前端試試這個。
前端 -
download2016(){
window.open("http://localhost:5000/download/report/2016")
}
后端代碼 -
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.