简体   繁体   English

PDF 使用 ReactJS MySql 生成成功但未在浏览器中显示为可下载

[英]PDF generated successfully but not showing as downloadable in the browser using ReactJS MySql

II am struggling to download the pdf file in browser, i have created the pdf at back end and can see the file locally in back end and then i save it in the mysql (screenshot below) and after that using API call i retrieve the pdf document to be downloadable on browser but it is showing filename as [object object] and status failed:no file when trying to download.我正在努力在浏览器中下载 pdf 文件,我在后端创建了 pdf,可以在后端本地看到该文件,然后我将它保存在 mysql(下面的屏幕截图)中,然后使用API call我检索 pdf文档可在浏览器上下载,但它显示文件名为 [object object] 并且状态failed:no file I have looked around and see some places to convert pdf to base64 but i am not sure if i need it.我环顾四周,看到一些地方可以将 pdf 转换为 base64,但我不确定是否需要它。 any suggestions please.请有任何建议。

snippet of backend-Nodejs code backend-Nodejs代码片段

  1. Backend - sending file through API call后端- 通过 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. Front end snippet of code前端代码片段
         
        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. Frontend code that triggers the API call触发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. when doing the console i get the following console.log("resxx", res)在执行控制台时,我得到以下console.log("resxx", res) 在此处输入图像描述 console.log("textxx", data); 在此处输入图像描述

If you are sending the above file through your API as an attachment then you want to use a javascript blob to read the file since it's non-native.如果您将上述文件作为附件通过 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>
)

Here we are creating a new Blob from the content sent through the API and then triggering a download popup to show up in the browser.在这里,我们根据通过 API 发送的内容创建一个新的 Blob,然后触发下载弹出窗口显示在浏览器中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM