我设法将上载到服务器功能上,但是我正努力从服务器下载。
我已成功从服务器接收文件,但是我不知道如何将其下载为文件或在新选项卡中打开(最好)。
所以在前端,我有一个Link
带有onClick的元素来发送请求:
<Link
onClick={(e) => {
handleDownloadInvoice(e, invoice.scannedFileName);
}}
href={``}
>
和反应中的处理功能:
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文件(最好在选项卡中打开)或作为文件下载到客户端计算机?
这是链接,可以提供帮助
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);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句