Reputation: 11
I want to use google drive api to upload some files to my drive using java The thing is that the upload is successfull but when i open my drive i can't find the file so i've edited the permission and added my email (to share it with me) but i can't download the file there is just the name of the upload any idea why ?
public static void connect() throws IOException, GeneralSecurityException {
UL.debug("Creating HTTP_TRANSPORT & a JSON_FACTORY");
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
UL.debug("Login-in with credentials");
GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(CREDENTIALS_FILE))
.createScoped(Collections.singleton(DriveScopes.DRIVE));
UL.debug("User: " + credential.getServiceAccountUser() + " ID: " + credential.getServiceAccountProjectId());
UL.debug("Creating Drive Instance");
DRIVE_SERVICE = new Drive.Builder(
HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName("Backup")
.build();
}
public static void upload() throws IOException {
UL.debug("Creating file metadata");
File fileMetadata = new File();
fileMetadata.setName("Test");
fileMetadata.setMimeType("application/rar");
UL.debug("creating new filepath");
java.io.File filePath = new java.io.File(DATA_FOLDER, "test3.rar");
UL.debug("Creating file content (rar)");
FileContent rarContent = new FileContent("application/rar", filePath);
UL.debug("Pushing the file to drive !");
Drive.Files.Create upload = DRIVE_SERVICE.files().create(fileMetadata, rarContent);
upload.getMediaHttpUploader().setProgressListener(new FileUploadProgressListener());
upload.setFields("*");
File e = upload.execute();
UL.debug("Push success: " + e.getId() + " " + e.getName() + " " + e.getMimeType());
Permission newPermission = new Permission();
newPermission.setEmailAddress("[email protected]");
newPermission.setType("user");
newPermission.setRole("writer");
DRIVE_SERVICE.permissions().create(e.getId(), newPermission).execute();
}
Upvotes: 1
Views: 116
Reputation: 26836
The way you doing it, the file will be uploaded to the service'accounts Drive - not to yours.
If you want to perform an upload with a service account which is supposed to act on your behalf (that is upload a file to YOUR drive), you need to use impersonation.
In java, when building DRIVE_SERVICE
, you have to add the line
.setServiceAccountId(emailAddress)
specifying the email address of the user on whose behalf the service account is supposed to act (so in this case - your email address).
Upvotes: 1