寻找例如使用 MediaFileUpload

问题描述

有谁知道我在哪里可以找到上传本地文件和使用 MediaFileUpload 获取内容的完整示例代码?

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

我真的需要查看用于发布的 HTML 表单和接受它的代码.我正在拔头发,到目前为止只得到部分答案.

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.


解决方案

我在试图找出 Google API 示例中的MediaFileUpload"到底是从哪里来的时候发现了这个问题,我最终弄明白了.这是我用来测试 Python 2.7 的更完整的代码示例.

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.

您需要一个 JSON 凭证文件才能使此代码正常工作.这是您从 Google 应用/项目/事物中获得的凭据文件.

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

你还需要一个文件来上传,我在这个例子中使用了test.html".

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

在body"哈希中使用的有效 Mime 类型列表可在https://developers.google.com/drive/v3/web/mime-types

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

MediaFileUpload 的有效 mimetype 字符串列表(它们会尝试将您的文件转换为您在此处放置的任何内容):

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

相关文章