2012-07-13 41 views
7

有誰知道在哪裏可以找到完整的示例代碼,用於上傳本地文件並獲取MediaFileUpload的內容?尋找使用MediaFileUpload的示例

我真的需要看到用於發佈的HTML表單以及接受它的代碼。我拉我的頭髮,迄今只獲得部分答案。

謝謝!

+0

當然,我們可以幫助你。你有什麼?粘貼它,我們可以修復它。順便說一下,您是否看到過這個問題:https://code.google.com/p/google-drive-sdk-samples/source/browse/#hg%2Fpython – 2012-07-13 15:14:18

+0

我已經遍歷了該代碼,但嘗試要使用它,找不到任何您希望發佈JSON的表單的示例。你能幫助我嗎?該表單應該是什麼樣子? – user1501783 2012-07-13 17:22:03

+0

查看此頁面:https://developers.google.com/drive/v3/web/folder#inserting_a_file_in_a_folder它有一個使用示例,可​​以幫助您 – Greg 2016-12-30 01:37:51

回答

7

我在找出這個問題的同時,試圖弄清楚Google API示例中heck「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')) 

有效的MIME類型的「正文」使用的名單哈希可在 https://developers.google.com/drive/v3/web/mime-types

爲MediaFileUpload有效的MIME類型的字符串列表(他們會嘗試將文件轉換爲任何你放在這裏):

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