how to upload pdf files to MongoDB

145 views
Skip to first unread message

charlene...@gmail.com

unread,
May 22, 2017, 5:27:56 AM5/22/17
to mongodb-user
Dears,

I have searched the method and found that GridFS might help. 

I refer the tutorial as below:

But there is one problem, I don't know how to insert the local address to the code. It means that I would like to specify the local address of a pdf file and upload it to the database, but I don't know how to do it. 

I also try to add the address of file into "put()" as:
a = fs.put("C:\Users\BAL_SP_EQUITY_57_25102016.pdf")

But it doesn't work, if you know the answer, please let me know.

Thanks.

Yumin

Kevin Adistambha

unread,
May 30, 2017, 11:33:31 PM5/30/17
to mongodb-user

Hi Yumin

a = fs.put("C:\Users\BAL_SP_EQUITY_57_25102016.pdf")
But it doesn’t work

The code you posted does work, but not in the manner you expect. It will put the string “C:\Users\BAL_SP_EQUITY_57_25102016.pdf” into GridFS instead of the pdf file. This is because the fs.put() method requires an instance of str (bytes in python 3) or a file-like object providing a read() method (see http://api.mongodb.com/python/current/api/gridfs/index.html#gridfs.GridFS.put).

To store the actual pdf file, you would need to open the pdf file first, and pass the file handle into the fs.put() method. For example:

f = open("C:\Users\BAL_SP_EQUITY_57_25102016.pdf", "rb")
a = fs.put(f, filename="BAL_SP_EQUITY_57_25102016.pdf")

You may find these links helpful:

Best regards,
Kevin

Reply all
Reply to author
Forward
0 new messages