21

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.

3
  • Sure, we can help you definitely. What have you got? Paste it and we can fix it. Have you seen this, by the way: code.google.com/p/google-drive-sdk-samples/source/browse/…
    – Ali Afshar
    Commented Jul 13, 2012 at 15:14
  • I've been all over that code, but when trying to use it, could not find any examples of what the form should you like to post the JSON. Can you help me with that? What should the form look like? Commented Jul 13, 2012 at 17:22
  • Check out this page: developers.google.com/drive/v3/web/… it has a usage example and may be able to help you
    – Greg
    Commented Dec 30, 2016 at 1:37

4 Answers 4

32

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

5
  • 2
    This code executes successfully but in my drive I am not seeing the file uploaded .What could be the possible reason for it?
    – Ricky
    Commented Jun 10, 2019 at 10:42
  • I'm looking for the reason too.. @Ricky, any chances you already find it?
    – Ardhi
    Commented Feb 6, 2021 at 4:55
  • 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.
    – Locane
    Commented Feb 7, 2021 at 5:51
  • 1
    apiclient is now googleapiclient i.e. from googleapiclient.http import MediaFileUpload
    – kztd
    Commented Mar 5, 2021 at 18:24
  • @Ardhi create a folder in your drive, share it with the email in your credential json, and add this key to the body dictionary: 'parents':["folder id here"]
    – grantr
    Commented Feb 24, 2023 at 1:07
5

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()

0

You won't need to post JSON yourself, the client library handles that for you.

We provide full code samples already which can be found here: https://github.com/gsuitedevs/python-samples

Also you could check the file.insert reference documentation which contains a Python sample: https://developers.google.com/drive/v2/reference/files/insert

If this does not answer what you want perhaps you could explain in more details what you want to achieve and your architecture currently in place.

1
0

I want to provide additional information on uploading to a specific drive folder. I am providing the example from my AWS Lambda with Python 3.7

Note:

  • You need the folder ID for your desired location. You can find this by going to your drive folder and looking for the ID in the URL in the Browser. For example in this URL, https://drive.google.com/drive/u/0/folders/1G91IKgQqI9YgNj8Odc8SIOPHrWOjdvOO, 1G91IKgQqI9YgNj8Odc8SIOPHrWOjdvOO would be your ID.
  • You need to provide your service account email access to the folder to be accessed. The service account email is found in the IAM section of your Google Cloud account. Add access to your folder by going to it in Drive, clicking the "i" icon on the top right, clicking details, then manage access.
  • You also need the JSON file associated with the service account. Find/create this in the Service Accounts section in Google Cloud IAM on the KEYS tab. The file contains the private key for your project. Store it where your code can access.
  • I'm not sure which dependencies you need to install but I think pydrive installed them all for me: pip3 install pydrive
from apiclient.discovery import build
from google.oauth2 import service_account
from googleapiclient.http import MediaFileUpload

# This provides what authority the service account has as well as the location of the JSON file containing the private key.
scopes = ['https://www.googleapis.com/auth/drive']
service_account_file = 'path/to/service_account.json'

# Create the credentials object for the service account
credentials = service_account.Credentials.from_service_account_file(service_account_file, scopes=scopes)
drive = build('drive', 'v3', credentials=credentials)

# Create the metadata for the file and upload it to the drive folder. Supply the corresponding MIME type for your file. The parents parameter is very important, this is where you supply the ID you found for your drive folder.
body = {'name': 'testfile.txt', 'mimeType': 'text/plain', 'parents': ["theStringForTheDriveFolder"]}
media = MediaFileUpload('path/to/testfile.txt', mimeType='text/plain')
drive.files().create(body=body, media_body=media).execute()

Here's the documentation I followed:

Not the answer you're looking for? Browse other questions tagged or ask your own question.