简体   繁体   English

React 从 Node 下载一个 pdf 文件并在选项卡中打开它

[英]React download a pdf file from Node and open it in a tab

I managed to get my upload to the server functionality work, however I am struggling with the download from the server.我设法让上传到服务器的功能正常工作,但是我正在努力从服务器下载。

I successfuly receive the file from the server, however I have no idea how to download it as a file or open it in a new tab (preferably).我成功地从服务器接收到文件,但是我不知道如何将其下载为文件或在新选项卡中打开它(最好)。

So on the front end I have, a Link element with onClick that sends the request:所以在前端我有一个带有 onClick 的Link元素,它发送请求:

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

and the handling function in react:和处理 function 反应:

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

From the server:从服务器:

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

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

So the logged invoiceFile has the data as a string, and it has the correct header: {content-type: "application/pdf" }所以记录的invoiceFile将数据作为字符串,并且它具有正确的header: {content-type: "application/pdf" }

The question is, how do I transform this data string back to a pdf file that either gets opened in a tab (preferably) or gets downloaded as a file to the clients computer?问题是,如何将此数据字符串转换回 pdf 文件,该文件要么在选项卡中打开(最好),要么作为文件下载到客户端计算机?

Here is link, which can help这是链接,可以提供帮助

https://medium.com/@storrisi/how-to-show-a-pdf-stream-on-a-react-client-without-any-library-36220fee60cb 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); });

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

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