简体   繁体   中英

how to upload an image from my android app to a specific folder on google drive

I'm using this code

to upload an image from my android app to the user's google drive account.

But how can I modify the code to upload the image to folder named "myFolder"?

meaning to that folder is exist and if not - create such folder and then upload the image there.

What you need to do in order to upload a file to a specific folder is to add the folder's id to the file parents ( ref Docs for file.insert ).

So the full things you need to do are:

  1. Find the folder in drive
  2. Create the insert request
  3. Add the parent id to the file insert
  4. Execute the insert request

Code

Find the Folder

Here you can opt for 2 ways: loop all the folders or search for it.

Faster and less resource heavy is to search the folder by name; to do so it's simple:

//Search by name and type folder
String qStr = "mimeType = 'application/vnd.google-apps.folder' and title = 'myFolder'";

//Get the list of Folders
FileList fList=service.files().list().setQ(qStr).execute();

//Check that the result is one folder
File folder;

if (fList.getItems().lenght==0){
    folder=fList.getItems()[0];

}

More info about the possible search parameters .

Create the insert request is as in the sample

File file = service.files().insert(body, mediaContent);

before executing it we need to set the parent file.setParents(Arrays.asList(new ParentReference().setId(folder.getFolderId())));

In the end execute the request file.execute();

I haven't tested the code so there might be some typo here and there.

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