java - 使用 oauth PlayGround (java) 上传到 Google Drive 不起作用
问题描述
我想使用google drive api使用java将一些文件上传到我的驱动器问题是上传成功但是当我打开驱动器时我找不到文件所以我编辑了权限并添加了我的电子邮件(到与我分享),但我无法下载文件,只有上传的名称,知道为什么吗?
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("eaglezledozo@gmail.com");
newPermission.setType("user");
newPermission.setRole("writer");
DRIVE_SERVICE.permissions().create(e.getId(), newPermission).execute();
}
解决方案
您正在使用服务帐户执行上传
你这样做的方式,文件将被上传到服务帐户驱动器 - 而不是你的驱动器。
如果您想使用应该代表您执行操作的服务帐户执行上传(即将文件上传到您的驱动器),您需要使用impersonation。
在java中,在构建时DRIVE_SERVICE
,您必须添加该行
.setServiceAccountId(emailAddress)
指定服务帐户应该代表其行事的用户的电子邮件地址(在这种情况下 - 您的电子邮件地址)。
推荐阅读
- python - Adjust timestamps on x-axis - Matplotlib
- node.js - Node/React:os.platform() 返回“浏览器”而不是实际的操作系统
- javascript - Internet Explorer 上的打字机效果:不删除字符串?
- react-native - visibility hidden on react native not working, to take space even not shown?
- android - 在 vivo v7 上使用 react-native-android-badge 不显示徽章或徽章计数
- scala - Scala 导入混淆
- javascript - 如何使用 php 查看从数据库获取到我的 gridview 的数据?
- dji-sdk - DJIGimbalRotation 可以在 p4 p 4 pro 中使用,但不能使用 spark
- java - 使用 Rest 模板的管道调用失败
- r - 当 x 轴是 r 中的日期格式时使用 plot abline()