Home > Software design >  Not able to download pdf-file (stored in binary data format) from Mongo-db using React JS
Not able to download pdf-file (stored in binary data format) from Mongo-db using React JS

Time:01-08

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: "[email protected]"                                                            
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/[email protected]');
        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 onClick={downloadPdf('pancard', contentType)}>Download

The file is also getting downloaded infinite times in loop

CodePudding user response:

There are many solutions for different file type:


Image (already tested for jpg):

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") 

PDF

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

This solution for PDF would work for all other types (including image) 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:

  • It is not recommend to save file data directly into database. Instead, save as static file and only store the path to database.
  • If file size exceed 16mb. We need to use GridFS for Mongo. More details: https://www.mongodb.com/docs/manual/core/gridfs/
  • Related