Search code examples
pythonpython-3.xgoogle-drive-api

How to upload files to Google Drive via memory [python]


I have been searching the forums with no success with regard to my question.

I am trying to use the Google Drive Python API to upload files that I have in memory to Google Drive. However, all examples that I have seen make use of a file on disk with a particular filepath and name.

 service = build('drive', 'v3', credentials=creds)

    media = MediaFileUpload(
        'MyFile.jpeg',
        mimetype='image/jpeg',
        resumable=True
    )
    request = service.files().create(
        media_body=media,
        body={'name': 'MyFile', 'parents': ['<your folder Id>']}
    )
    response = None
    while response is None:
        status, response = request.next_chunk()
        if status:
            print("Uploaded %d%%." % int(status.progress() * 100))
    print("Upload Complete!")

However, I want to do something like this:

with open('MyFile.jpeg', 'rb') as FID: 
	fileInMemory = FID.read()
	
myGDriveUpload(fileInMemory)

#Pass jpeg file that has been read into memory
#to Google Drive for upload.

The file will be in memory due to the operations that I am doing, and it would be unnecessary to save to disk, upload the file using its filepath, and then delete the file that has been temporarily saved on disk.

How would it be possible to just upload the file as it is in memory without having to save it to disk and use a filepath and name?

Thanks


Solution

    • You want to upload the data in the memory to Google Drive using googleapis with python.
    • You want to use fileInMemory of the following script.

      with open('MyFile.jpeg', 'rb') as FID: 
          fileInMemory = FID.read()
      
    • You have already been able to upload a file using Drive API.

    In this answer, I used "Class MediaIoBaseUpload" instead of "Class MediaFileUpload".

    Sample script:

    service = build('drive', 'v3', credentials=creds)
    
    with open('MyFile.jpeg', 'rb') as FID:
        fileInMemory = FID.read()
    
    media = MediaIoBaseUpload(io.BytesIO(fileInMemory), mimetype='image/jpeg', resumable=True)
    request = service.files().create(
        media_body=media,
        body={'name': 'MyFile', 'parents': ['<your folder Id>']}
    )
    response = None
    while response is None:
        status, response = request.next_chunk()
        if status:
            print("Uploaded %d%%." % int(status.progress() * 100))
    print("Upload Complete!")
    

    Reference: