5

I am using PyDrive to create files in Google Drive, but I'm having trouble with the actual Google Doc type items.

My code is:

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

file.SetContentString("Hello World")

file.Upload()

This works fine if I change the mimetype to text/plain but as is it gives me the error:

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

It also works fine if I leave the MimeType as is, but remove the call to SetContentString, so it appears those two things don't behave well together.

What is the proper way to create a Google Doc and set the content?

awestover89
  • 1,713
  • 4
  • 21
  • 37
  • Additional: Based from this [documentation](https://developers.google.com/drive/v3/reference/files/create), Drive will attempt to automatically detect an appropriate value from uploaded content if no value is provided. The value cannot be changed unless a new revision is uploaded. Here's a related thread: https://stackoverflow.com/questions/43988753/googles-file-insert-v2-api-fails-to-recognise-mime-type-application-vnd-google – abielita Jul 31 '17 at 15:36

1 Answers1

8

Mime type must match the uploaded file format. You need a file in one of supported formats and you need to upload it with matching content type. So, either:

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

This file can be accessed via Google Notebook. Or,

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

which can be opened with Google Docs. List of supported formats and corresponding mime types can be found here.

To convert file on the fly to Google Docs format, use:

file.Upload(param={'convert': True})
Maciej Małycha
  • 405
  • 6
  • 8
  • That just seems so counter-intuitive. In order to use Google Docs proprietary format with the Google Docs API I have to upload a different format and convert... Having it as text/plain and then adding the convert command to the Upload worked, thanks – awestover89 Jul 31 '17 at 15:06