How to upload a streamlit file to google drive

Hello everyone,
I am having a bit of a problem uploading a pdf file to Google drive. I am trying to create a form which also entails the user uploading a document with the .pdf extension.
So far I have this, but obviously it does´s work:

pm = st.file_uploader(“Upload your file”, type=“pdf”)
gauth.LocalWebserverAuth()
gfile = drive.CreateFile({‘parents’: [{‘id’: drive_key}], “title”: pm.name})
gfile.SetContentFile(pm.name)
gfile.Upload()

I would appreciate any help :slight_smile:

Hi @lukecpukec,

I haven’t used pydrive before, but I think something like this should work. The basic issue is that an uploaded file is just in-memory, and not saved to disk, but you can use a temporary file to get around this.

from tempfile import NamedTemporaryFile

pm = st.file_uploader("Upload your file", type=“pdf”)
with NamedTemporaryFile() as f:
    f.write(pm.getvalue())
    gauth.LocalWebserverAuth()
    gfile = drive.CreateFile({‘parents’: [{'id': drive_key}], "title": pm.name})
    gfile.SetContentFile(f.name)
    gfile.Upload()
1 Like

Hey @blackary, it worked but the file that gets uploaded to drive is damaged and cannot be opened. Is there a reason for this?

No, I can’t think of a specific reason. You might try:

  1. Put a pdf in the folder with your app
  2. Upload that file
  3. Check to see if it gets damaged

Hopefully that will help narrow down what is causing the issue.

Nevermind, the pdf file was indeed damaged from before. Thank you for everything :heart: :sunglasses:

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.