Looking for example using MediaFileUpload

后端 未结 3 969
情书的邮戳
情书的邮戳 2020-12-16 12:44

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

相关标签:
3条回答
  • 2020-12-16 13:07

    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

    0 讨论(0)
  • 2020-12-16 13:11

    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.

    0 讨论(0)
  • 2020-12-16 13:15

    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 讨论(0)
提交回复
热议问题