20

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

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

4

3 回答 3

31

我在试图找出 Google API 示例中的“MediaFileUpload”来自哪里时发现了这个问题,我最终弄明白了。这是一个更完整的代码示例,我用它来测试 Python 2.7。

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

您还需要上传一个文件,我在示例中使用“test.html”。

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获得

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

https://developers.google.com/drive/v3/web/integrate-open#open_files_using_the_open_with_contextual_menu

于 2016-05-24T21:12:48.117 回答
3

Python 2.7,可恢复上传。

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

于 2020-03-12T04:49:58.420 回答
0

您不需要自己发布 JSON,客户端库会为您处理。

我们已经提供了完整的代码示例,可以在这里找到:https ://github.com/gsuitedevs/python-samples

您还可以查看包含 Python 示例的 file.insert 参考文档:https ://developers.google.com/drive/v2/reference/files/insert

如果这不能回答您想要的,也许您可​​以更详细地解释您想要实现的目标以及您当前的架构。

于 2012-07-16T23:33:40.853 回答