如何在Reactjs中打开保存在本地驱动器中的pdf文件,其路径来自后端(ExpressJS)?
实际上,我在表格中显示了一些数据,表格的每一行本身就是一个链接。我想通过单击一行来打开相关的pdf。由于DB是Mongo,因此我可以为pdf提供每个文档的单独链接。到目前为止,我正在使用axios从后端获取数据。如何编写代码,以便可以使用后端的链接单击表格的行来打开pdf?
请帮助我该怎么做。
答案 0 :(得分:0)
尝试以下代码: 只需在视图处理程序中传递此代码
viewHandler = async () => {
axios(your Api url, {
method: "GET",
responseType: "blob"
//Force to receive data in a Blob Format
})
.then(response => {
//Create a Blob from the PDF Stream
const file = new Blob([response.data], {
type: "application/pdf"
});
//Build a URL from the file
const fileURL = URL.createObjectURL(file);
//Open the URL on new Window
window.open(fileURL);
})
.catch(error => {
console.log(error);
});
答案 1 :(得分:0)
您需要从API端点获取PDF数据
axios(${apiURL}/PDF
,{
方法:“获取”,
答案 2 :(得分:0)
后端(NodeJ)的代码:
// id对于表中的每个链接(行)都是唯一的,基于'id',从DB提取数据,并从Node返回该特定ID的pdf
app.get('/papers/:id', (req, res) => {
connectionForPdf(req.params.id).then((data)=>{
var tempFile=data.paperLocation; //data.paperLocation physical path of the paper
//fetched from DB
fs.readFile(tempFile, function (err,data){
res.contentType("application/pdf");
res.send(data);
});
})
.catch(error=>{
console.log('Shit');
})
})
connectionForPdf=(id)=>{
return mongoose.connect(url,{ useNewUrlParser: true, useUnifiedTopology: true })
.then((database)=> {
return exampleModel.findOne({_id:id}).then(data=>{
if(data) {
return data.toObject();
}
database.close();
}).catch(error=>{
console.log('Con')
})
.catch((error)=>{
console.log('not connected')
let err=new Error("Couldn't connect");
err.status=500;
throw err;
})
}
前端代码(ReactJs):
// id在每个链接(行)的onClick()上传递
handleClick=(id)=>{
const viewHandler = async () => {
axios('http://localhost:3001/papers/'+id, {
method: "GET",
responseType: "blob"
//Force to receive data in a Blob Format
})
.then(response => {
//Build a URL from the file
var file = new Blob([response.data], {type: 'application/pdf'});
const fileURL = URL.createObjectURL(file);
//Open the URL on new Window
window.open(fileURL);
})
.catch(error => {
console.log(error);
});
}
viewHandler();
}