2017-07-31 96 views
2

我使用PyDrive在Google Drive中創建文件,但我在實際的Google Doc類型項目中遇到了問題。PyDrive:創建一個Google Doc文件

我的代碼是:

file = drive.CreateFile({'title': pagename, 
"parents": [{"id": folder_id}], 
"mimeType": "application/vnd.google-apps.document"}) 

file.SetContentString("Hello World") 

file.Upload() 

如果我改變MIME類型,以text/plain這工作得很好,但因爲是它給我的錯誤:

raise ApiRequestError(error) pydrive.files.ApiRequestError: https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable&alt=json returned "Invalid mime type provided">

,如果我離開的MimeType它也能正常工作原樣,但刪除了對SetContentString的調用,所以看起來這兩件事情並不一致。

什麼是創建Google文檔並設置內容的正確方法?

+0

附加:從這個[文件]根據(https://developers.google.com/drive/v3/reference/files/創建),如果未提供任何值,雲端硬盤將嘗試自動檢測上傳內容的適當值。除非上傳新版本,否則無法更改該值。這裏有一個相關的線程:https://stackoverflow.com/questions/43988753/googles-file-insert-v2-api-fails-to-recognise-mime-type-application-vnd-google – abielita

回答

2

Mime類型必須匹配上傳的文件格式。您需要一種支持格式的文件,並且需要使用匹配的內容類型上傳文件。因此,要麼:

file = drive.CreateFile({'title': 'TestFile.txt', 'mimeType': 'text/plan'}) 
file.SetContentString("Hello World") 
file.Upload() 

可以通過Google筆記本訪問此文件。或者,

file = drive.CreateFile({'title': 'TestFile.doc', 
         'mimeType': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'}) 
file.SetContentFile("TestFile.docx") 
file.Upload() 

它可以使用Google文檔打開。支持的格式列表和相應的MIME類型可以在here找到。

要轉換的文件在運行到谷歌文檔格式,使用方法:

file.Upload(param={'convert': True}) 
+0

這似乎是反直覺。爲了使用Google Docs專有格式和Google Docs API,我必須上傳不同的格式並進行轉換...將其作爲文本/純文本格式,然後將轉換命令添加到Upload工作,謝謝 – awestover89