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:
- Find the folder in drive
- Create the insert request
- Add the parent id to the file insert
- 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.