【问题标题】:PDF generated successfully but not showing as downloadable in the browser using ReactJS MySql使用 ReactJS MySql 成功生成 PDF 但无法在浏览器中显示为可下载
【发布时间】:2020-11-19 00:18:41
【问题描述】:

我正在努力在浏览器中下载 pdf 文件,我已经在后端创建了 pdf,并且可以在后端本地查看该文件,然后我将其保存在 mysql 中(下面的屏幕截图),然后使用 API call我检索到可在浏览器上下载的 pdf 文档,但在尝试下载时显示文件名为 [object object] 和状态 failed:no file。 我环顾四周,看到一些将 pdf 转换为 base64 的地方,但我不确定我是否需要它。请有任何建议。

sn-p of backend-Nodejs 代码

  1. 后端-通过API调用发送文件
     let token = req.cookies.access_token;
     if (token) {
       let Invoice_No_Actual = req.body.invoice_Name;
// the below two res.set has been set now

     res.set("Content-disposition", "attachment; filename=" + `${__dirname}\\` + `${Invoice_No_Actual}` + `.pdf`);
               res.contentType("application/pdf");

  res.send(`data:application/pdf;base64,${new Buffer.from(data).toString("base64")}`);
     }
   });
  1. 前端代码的sn-p
         
        console.log("content", content);// this content if i convert online tool it does shows the correct PDF file 
        
    
        const blob = new Blob([content], { type: "application/pdf" });
        console.log(blob);
        const link = document.createElement("a");
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
      };
     const generatePdf = (invoice_Name) => {
        let invoice_Object = {
          invoice_Name: invoice_Name,
        };

    const headers = new Headers();
    headers.append("content-type", "application/json");
    headers.append("responseType", "blob");
    // headers.append("responseType", "blob");
    const options = {
      method: "POST",
      headers,
      credentials: "include",
      body: JSON.stringify(invoice_Object),
    };
    const newRequest = new Request("http://localhost:5000/api/invoice-only", options);

    (async () => {
      const invoice_Call = await fetch(newRequest)
        .then((res) => {
           
          return res.text();  
          
        })
        .then((data) => {
          
          generateFile(data, invoice_Name);
        });
    })();
  };
  1. 触发API call前端代码

     let invoice_Name = `${users_user_id}` + `_` + `${invoiceNo}`; 
// to get the specific invoice (userid_invoiceNO) usefull to get specific file from backend
        <span role="button" tabIndex="-1" onKeyDown={() => generatePdf(invoice_Name)} onClick={() => generatePdf(invoice_Name)}>invoiceNo:{invoiceNo}
         </span>

  1. 在执行控制台时,我得到以下信息 console.log("resxx", res) console.log("textxx", data);

【问题讨论】:

    标签: javascript mysql node.js reactjs


    【解决方案1】:

    如果您通过 API 将上述文件作为附件发送,那么您希望使用 javascript blob 来读取该文件,因为它不是本地文件。

    const generateFile = (content, fileName) => {
      const blob = new Blob([content]);
      const link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = fileName;
      link.click();
    }
    
    const generatePdf = () => {
      (...some api request here)
        .then(res => {
            ...catching the response here
            const filename = 'new_file.pdf'; // You can get this name from the API
            generateFile(res, filename))
        .catch(.....)
    }
    
    return (
      <span
          role="button"
          tabIndex="-1"
          onKeyDown={generatePdf}
          onClick={generatePdf}
        >
         Download PDF
        </span>
    )
    

    在这里,我们从通过 API 发送的内容创建一个新的 Blob,然后触发下载弹出窗口以显示在浏览器中。

    【讨论】:

    • 感谢您的回答,对不起,我对这一切有点陌生。我将在哪里使用上述函数是在 标签 时,下载将使文件可下载
    • @Umair_007 我更新了问题以添加一个完整的示例以及渲染函数和带有 api 调用的函数。如果您有任何问题,请告诉我
    • 再次感谢,我在设置后端发送文件时遇到了一些问题,但现在它似乎正在发送文件,但我仍然无法打开 pdf,我已经更新了上面的代码。我已尝试按照您的建议实施,但不确定我现在到底缺少什么。
    • 我添加的附加内容是 const text1 = res.text();否则它要求解决,除非我可以使用其他东西来解决它。
    • @Umair_007 你的意思是你可以成功下载 pdf 但它不会打开或者下载的弹出窗口永远不会出现?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 2018-02-04
    • 1970-01-01
    相关资源
    最近更新 更多