0

I've been struggling for days with this. I am trying to have users upload an avatar (very small image file) directly to my Drive account from an HTML input element.

I created a service account and in the code below I am using its credentials to perform the upload.

The img_path comes from the input element.

    from google.oauth2 import service_account
    from googleapiclient.discovery import build
    from googleapiclient.http import MediaFileUpload

    credentials_file = os.path.dirname(os.path.realpath(__file__)) + '/mycredentials-cad0bbacb5f8.json'

    credentials = service_account.Credentials.from_service_account_file(
        credentials_file)

    scoped_credentials = credentials.with_scopes(
        ['https://www.googleapis.com/auth/drive'])

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

    body = {
        'name': img_path.split("/")[-1],
    }

    media_body = MediaFileUpload(
            img_path,
            mimetypes.guess_type(img_path)[0],
    )

    file = service.files().create(body=body, media_body=media_body).execute()

I get the following output, which is what is expected, but I cannot see the file anywhere in my Google Drive account:

{'kind': 'drive#file', 'id': '<FILE_ID>', 'name': '<UPLOADED_FILE>', 'mimeType': '<MIME_TYPE>'}

What am I doing wrong?

UPDATE

I stumbled into this post, where it is said that apparently I am uploading files to the service account's Google Drive space, not my own.

UPDATE #2

The code I posted above is actually correct, but a few things should be pointed out in order to make it upload to your own personal Google Drive.

  1. Add the parents key-value pair to MediaFileUpload's body. The request host will be automatically passed multipart encoded data.
  2. Be sure the service account email has got the permissions on that exact folder (you can do it via the Google Drive UI, too).

The working code, inclusive of the parents pair, is the following:

    from google.oauth2 import service_account
    from googleapiclient.discovery import build
    from googleapiclient.http import MediaFileUpload

    credentials_file = os.path.dirname(os.path.realpath(__file__)) + '/mycredentials-cad0bbacb5f8.json'

    credentials = service_account.Credentials.from_service_account_file(
        credentials_file)

    scoped_credentials = credentials.with_scopes(
        ['https://www.googleapis.com/auth/drive'])

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

    body = {
        'name': img_path.split("/")[-1],
        'parents': '<FOLDER-ID>'
    }

    media_body = MediaFileUpload(
            img_path,
            mimetypes.guess_type(img_path)[0],
    )

    file = service.files().create(body=body, media_body=media_body).execute()

0 Answers0