寻找使用 MediaFileUpload 的示例 [英] Looking for example using MediaFileUpload

查看:24
本文介绍了寻找使用 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

这篇关于寻找使用 MediaFileUpload 的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆