简体   繁体   中英

Unable to upload file in specific folder in google drive using REST API

I am trying to upload a local file to a specified folder in Google Drive using REST API from android app, the file is uploading in the root directory but not uploading in the specified folder. No error in the API.

Using the following API: https://developers.google.com/drive/api/guides/manage-uploads#multipart

Tried passing the folder ID in metadata in following ways:

1.

String[] arr = {parentFolderId};    
jsonObject.put("parents", arr);
jsonObject.put("name", file.getName());
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("id", parentFolderId);
jsonArray.put(jsonObject1);
jsonObject.put("parents", jsonArray);
jsonObject.put("name", file.getName());
ArrayList<String> arrayList = new ArrayList<>(); 
arrayList.add(parentFolderId);
jsonObject.put("parents", arrayList);
jsonObject.put("name", file.getName());

"parents" parameter isn't working, also tried using "addParents" parameter. Kindly suggest a way to specify the parent folder ID.

I am not a java or android expert but this may get you started.

String folderId = "folderID";
File fileMetadata = new File();
fileMetadata.setName("FileName");
fileMetadata.setParents(Collections.singletonList(folderId));

File file = driveService.files().create(fileMetadata)
.setFields("id, parent")
.execute();
System.out.println("File ID: " + file.getId());

or maybe this

String UploadFileToGoogleDrive(String sFullPath, String sFileName, String sParentFolderId) {               
    com.google.api.services.drive.model.File fileMetadata = new com.google.api.services.drive.model.File();
    fileMetadata.setName(sFileName);
    fileMetadata.setParents(Collections.singletonList(sParentFolderId));
    java.io.File filePath = new java.io.File(sFullPath);
    FileContent mediaContent = new FileContent(null, filePath);
    try {
        com.google.api.services.drive.model.File file = googleDriveService.files().create(fileMetadata, mediaContent)
                .setFields("id, parents")
                .execute();
        return file.getId();
    } catch (IOException e) {            
        return null;
    }       
}

pure rest html

Im not exactly usre what you mean by "I am using REST API." but if you are trying to do this completely yourself make sure that you build the body properly that is where the metadata is submited.

POST https://www.googleapis.com/drive/v3/files?key=[YOUR_API_KEY] HTTP/1.1

Authorization: Bearer [YOUR_ACCESS_TOKEN]
Accept: application/json
Content-Type: application/json

{
  "name": "test",
  "parents": [
    "folderId"
  ]
}

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