【问题标题】:React download a pdf file from Node and open it in a tabReact 从 Node 下载一个 pdf 文件并在选项卡中打开它
【发布时间】:2021-01-14 21:03:43
【问题描述】:

我设法让上传到服务器的功能正常工作,但是我在从服务器下载时遇到了困难。

我成功地从服务器接收到文件,但是我不知道如何将其下载为文件或在新选项卡中打开它(最好)。

所以在前端我有一个带有 onClick 的 Link 元素来发送请求:

<Link
  onClick={(e) => {
    handleDownloadInvoice(e, invoice.scannedFileName);
  }}
  href={``}
>

以及react中的处理函数:

const handleDownloadInvoice = async (e, fileName) => {
  e.preventDefault();

  const invoiceFile = await axios.get(`http://localhost:3000/api/v1/invoice/getfile/${fileName}`, {
    headers: { "x-access-token": localStorage.getItem("token") },
  });

  console.log(invoiceFile);
};

来自服务器:

const getScannedFile = async (req, res) => {
  const { fileName } = req.params;

  res.contentType("application/pdf").sendFile(__basedir + `\\uploadedFiles\\invoices\\${fileName}`);
};

所以记录的invoiceFile 具有字符串形式的数据,并且它具有正确的header: {content-type: "application/pdf" }

问题是,如何将此数据字符串转换回 pdf 文件,该文件可以在选项卡中打开(最好)或作为文件下载到客户端计算机?

【问题讨论】:

  • @Sam 我不明白这对我有什么帮助,我正处于从服务器接收文件作为invoiceFile.data 中的字符串的地步,我不知道也不能t 找到如何从那里开始的信息。文件也存储在 nodejs 服务器中,而不是在 react 应用程序中。另外我不想在应用程序中显示它,我想在新窗口中打开它并将文件保存到客户端的计算机上。
  • 我在这种情况下使用jspdf

标签: javascript reactjs


【解决方案1】:

这里是链接,可以帮到你

https://medium.com/@storrisi/how-to-show-a-pdf-stream-on-a-react-client-without-any-library-36220fee60cb

axios(`${apiURL}/pdf`, {
   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);
});

【讨论】:

    猜你喜欢
    • 2020-03-02
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 2016-02-15
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多