2017-04-20 105 views
0

此脚本适用于小文件,但不适用于我尝试上传大文件(250MB)的情况。当我手动将相同的大文件上传到GD时,只需不到10秒,所以我假设我的连接不是问题。上传大文件无效 - Google Drive Python API

upload.py

from __future__ import print_function 
import os 
import sys 

from apiclient.http import MediaFileUpload 
from apiclient.discovery import build 
from httplib2 import Http 
from oauth2client import file, client, tools 

try: 
    import argparse 
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() 
except ImportError: 
    flags = None 

SCOPES = 'https://www.googleapis.com/auth/drive.file' 
store = file.Storage(r'C:\Users\lucas.rezende\.credentials\storage.json') 
creds = store.get() 

if not creds or creds.invalid: 
    flow = client.flow_from_clientsecrets(r'C:\Users\lucas.rezende\.credentials\client_secret.json', scope=SCOPES) 
    creds = tools.run_flow(flow, store, flags) if flags else tools.run(flow, store) 
DRIVE = build('drive', 'v3', http=creds.authorize(Http())) 

FILES = (
    ('OfertasMensais_20170418_n.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'), 
) 

for filename, mimeType in FILES: 

    media_body = MediaFileUpload(filename, chunksize=1024*256, resumable = True) 

    folder_id = '0000' 
    metadata = {'name': filename, 'parents': [folder_id]} 

    if mimeType: 
     metadata['mimeType'] = mimeType 
    res = DRIVE.files().create(body=metadata, media_body=filename).execute() 

    if res: 
     print('Uploaded "%s" (%s)' % (filename, res['mimeType'])) 

当我运行CMD python uploadfile.py屏幕保持这样永远:

有人能帮助发现如何使这项工作?我不是一个专业的程序员,我为此付出了近两个小时的努力。

+0

你从哪里得到这种MIME类型? http://stackoverflow.com/a/36957953/130453 – corn3lius

+0

@ corn3lius我从这篇文章的第三个答案得到:http://stackoverflow.com/questions/11894772/google-drive-mime-types-listing,但实际上我不想转换。只需将我的xlsx文件上传到GD。 –

+0

你尝试过'application/vnd.ms-excel'吗? – corn3lius

回答

0

继分块范例之后,您需要专门拨打next_chunk()继续上传。看到这里:https://developers.google.com/api-client-library/python/guide/media_upload#resumable-media-chunked-upload

for filename, mimeType in FILES: 
    media_body = MediaFileUpload(filename, chunksize=1024*256, resumable = True) 

    if mimeType: 
     metadata['mimeType'] = mimeType 

    req = DRIVE.files().insert(body=metadata, media_body=filename) 
    res = None 
    while res is None: 
     status, res = req.next_chunk() 
     if status : 
      print('Uploading %d%% "%s" (%s)' % (status.progress(), filename, res['mimeType'])) 
    print("Upload Complete!") 
+0

我更新了我的代码,但它似乎缺少一些导入。我得到了一个'NameError:name'请求'不是ndefined'。我现在是为了它。 –

+0

从我你送我也可以从'MediaFileUpload'删除'CHUNKSIZE = 1024 * 256'单个请求链接阅读... –

+0

@LucasRezende只是edittied吧'req'是'request'。你也可以这样做!你也需要删除'resumeable'标志。 – corn3lius