I used express-fileuplod for uploading the pdf file on Mongodb. I am facing problem to download that pdf file on front end.
I'm getting this prompt after downloading the pdf: "Error. Failed to load PDF document"
form-data on MongoDB:
_id: ObjectId('63b7494295b850d0452a6a81')
username: "sita"
email: "sita@gmail.com"
dob: 2023-01-01T00:00:00.000+00:00
city: "city"
address: "add"
services: Array
0: "Demat"
pancard: Object
Data:BinData(0,'JVBERi0xLjcKCjQgMCBvYmoKPDwKL0ZpbHRlciAvRmxhdGVEZWNvZGUKL0xlbmd0aCAzMDEzNQo+PgpzdHJlYW0KeJztvU1247gS…')
ContentType: "application/pdf"
createdAt: 2023-01-05T22:03:46.893+00:00
updatedAt: 2023-01-05T22:03:46.893+00:00
__v: 0
[reactjs code:]
React.useEffect(()=>{
const fetchClient = async () =>{
const res = await axios.get('/users/sita@gmail.com');
setData(res.data.pancard.Data.data);
setContentType(res.data.pancard.contentType)
}
fetchClient()
},[userdetail]);
const downloadPdf = (filename, contentType) => {
const file = new Blob([data], { type: contentType });
saveAs(file, "pancard.pdf")
//const fileURL = URL.createObjectURL(file);
//window.open(fileURL);
};
Calling downloadpdf() method here in JSX
<button class="btn btn-primary button" onClick={downloadPdf('pancard', contentType)}>Download
The file is also getting downloaded infinite times in loop
Solution 1
That data
is only an Array, we need to convert to Uint8Array
const file = new Blob([new Uint8Array(data)], { type: contentType });
saveAs(file, "pancard.pdf")
Solution 2
We have to serve file on another route, it can not be sent with json data
backend
// Example in Express
app.get('/get_file', (req, res) => {
// Query user
res.set('Content-Disposition', 'attachment; filename="test.pdf"');
res.set('Content-Type', 'application/pdf');
res.send(user.pancard);
}
frontend
fetch('http://localhost:8000/get_file')
.then(res => res.blob())
.then(data => {
saveAs(data, 'test.pdf');
})
With large file, Solution 2 is better thanks to the Content-Disposition
header. File data is transferred safely with this header (I don't really understand the underlying mechanism, please research further)
Also notice 2 things: