Reputation: 3434
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:
<Link
onClick={(e) => {
handleDownloadInvoice(e, invoice.scannedFileName);
}}
href={``}
>
and the handling function in 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);
};
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" }
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?
Upvotes: 0
Views: 2414
Reputation: 1239
Here is link , which can help
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); });
Upvotes: 2