Looking for example using MediaFileUpload

22,577

Solution 1

I found this question while trying to figure out where the heck "MediaFileUpload" came from in the Google API examples, and I eventually figured it out. Here is a more complete code example that I used to test things with Python 2.7.

You need a JSON credentials file for this code to work. This is the credentials file you get from your Google app / project / thing.

You also need a file to upload, I'm using "test.html" here in the example.

from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
from apiclient.http import MediaFileUpload

#Set up a credentials object I think
creds = ServiceAccountCredentials.from_json_keyfile_name('credentials_from_google_app.json', ['https://www.googleapis.com/auth/drive'])

#Now build our api object, thing
drive_api = build('drive', 'v3', credentials=creds)

file_name = "test"
print "Uploading file " + file_name + "..."

#We have to make a request hash to tell the google API what we're giving it
body = {'name': file_name, 'mimeType': 'application/vnd.google-apps.document'}

#Now create the media file upload object and tell it what file to upload,
#in this case 'test.html'
media = MediaFileUpload('test.html', mimetype = 'text/html')

#Now we're doing the actual post, creating a new file of the uploaded type
fiahl = drive_api.files().create(body=body, media_body=media).execute()

#Because verbosity is nice
print "Created file '%s' id '%s'." % (fiahl.get('name'), fiahl.get('id'))

A list of valid Mime Types to use in the "body" hash is available at https://developers.google.com/drive/v3/web/mime-types

A list of valid mimetype strings for the MediaFileUpload (they'll attempt to convert your file to whatever you put here):

https://developers.google.com/drive/v3/web/integrate-open#open_files_using_the_open_with_contextual_menu

Solution 2

Python 2.7, resumable upload.

https://github.com/googleapis/google-api-python-client/blob/master/docs/media.md

from __future__ import print_function
import pickle
import os.path
from googleapiclient.http import MediaFileUpload
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive']


def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

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

    media = MediaFileUpload(
        'big.jpeg',
        mimetype='image/jpeg',
        resumable=True
    )
    request = service.files().create(
        media_body=media,
        body={'name': 'Big', '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!")


if __name__ == '__main__':
    main()

Share:
22,577
user1501783
Author by

user1501783

Updated on October 05, 2021

Comments

  • user1501783
    user1501783 over 2 years

    Does anyone know where I can find complete sample code for uploading a local file and getting contents with MediaFileUpload?

    I really need to see both the HTML form used to post and the code to accept it. I'm pulling my hair out and so far only getting partial answers.

  • ethanenglish
    ethanenglish over 5 years
    Do you have an updated link for github.com/googledrive/#hg%2Fpython? Github is saying: "This organization has no public repositories."
  • Ricky
    Ricky almost 5 years
    This code executes successfully but in my drive I am not seeing the file uploaded .What could be the possible reason for it?
  • Ardhi
    Ardhi about 3 years
    I'm looking for the reason too.. @Ricky, any chances you already find it?
  • Locane
    Locane about 3 years
    If I had to take a wild guess I'd say it's uploaded to a default directory or no directory - the object association you upload too is important; Google Drive API (or at least when I did this 5 years ago...) can treat ANY object like a folder, and you can end up uploading a document under another document, for example.
  • kztd
    kztd about 3 years
    apiclient is now googleapiclient i.e. from googleapiclient.http import MediaFileUpload