Looking for example using MediaFileUpload

强颜欢笑 提交于 2020-01-10 01:04:22

问题


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.

Thanks!


回答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




回答2:


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.



来源:https://stackoverflow.com/questions/11472401/looking-for-example-using-mediafileupload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!