2017-04-20 42 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