简体   繁体   中英

Upload a new document to Google drive from my android application

I am trying to create a new document on Google Drive from my android application using Google Drive SDK. My authentication is working and I have managed to create a simple text file with this code:

// com.google.api.services.drive.model.File
File newFile = new File();
newFile.setTitle("Test");
newFile.setMimeType("text/plain");
String contentStr = "This is a test file";      

try {
    File insertedFile = drive.files().insert(
         newFile, ByteArrayContent.fromString("text/plain", contentStr)).execute();
} catch (IOException e) {
    e.printStackTrace();
}

If I change "text/plain" to "application/vnd.google-apps.document" and insert the file without any content it works and a new document is created on my Google Drive:

// com.google.api.services.drive.model.File
File newFile = new File();
newFile.setTitle("Test");
newFile.setMimeType("application/vnd.google-apps.document");   

try {
    File insertedFile = drive.files().insert(newFile).execute();
} catch (IOException e) {
     e.printStackTrace();
}

But I want to upload a new document with content but when using the same approach as with the plain text file:

// com.google.api.services.drive.model.File
File newFile = new File();
newFile.setTitle("Test");

String fileType = "application/vnd.google-apps.document";
newFile.setMimeType(fileType);   

try {
    File insertedFile = drive.files().insert(
              newFile, ByteArrayContent.fromString(fileType, contentStr)).execute();
} catch (IOException e) {
    e.printStackTrace();
}

I get this error:

 com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
 {
     "code" : 400,
     "errors" : [ {
          "domain" : "global",
          "message" : "Bad Request",
          "reason" : "badRequest"
     } ],
     "message" : "Bad Request"
 }

And no file is created. Please can someone help me?

The mime type must be the mime type of the source document, eg text/plan or text/HTML. If you upload with convert=true, the resulting file on Drive will have a mime type of application/vnd.google-apps.document.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM