【问题标题】:Open a pdf in React by getting path from Node JS通过从 Node JS 获取路径在 React 中打开 pdf
【发布时间】:2019-11-12 16:08:53
【问题描述】:

如何在 Reactjs 中打开保存在本地驱动器中且路径来自后端(ExpressJS)的 pdf?

实际上,我在 Table 中显示了一些数据,Table 的每一行本身就是一个链接。我想通过单击一行来打开相关的 pdf。因为,DB 是 Mongo,所以我可以为每个 pdf 文档提供单独的链接。截至目前,我正在使用 axios 从后端获取数据。如何编写代码,以便我可以通过使用后端链接单击表格的行来打开 pdf?

请帮帮我,我该怎么做。

【问题讨论】:

    标签: node.js reactjs express pdf


    【解决方案1】:

    您需要从 API 端点获取 PDF 数据

    axios (${apiURL}/PDF, {

    方法:'GET',

    【讨论】:

      【解决方案2】:

      试试这个代码: 只需在视图处理程序中传递此代码

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

      【讨论】:

      • 我试过这段代码,但 pdf 没有打开。我的数据来自后端,如下所示: { "_id": { "$oid": "5d8ce1f234e1c2c2eb5c226" }, "papertype": "Maths", "paperLocation": "Maths_Paper/Maths.pdf" } fileURL 正在生成一些输出,但我没有得到它。如何调整此代码以打开 pdf 文件?
      【解决方案3】:

      后端代码(NodeJs):

      //id对于表中的每个Link(行)都是唯一的,基于'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在每个Link(Row)的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();
            }
      

      【讨论】:

        猜你喜欢
        • 2019-05-24
        • 1970-01-01
        • 2013-06-16
        • 2017-05-16
        • 1970-01-01
        • 2020-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多