问题描述
我使用以下 Java 代码通过 REST Api v3 将文件从我的 Android 应用上传到 Google Drive:
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;
}
}
boolean DownloadFileFromGoogleDrive(String sFileId,String sDestinationPath) {
try {
FileOutputStream oFileOutputStream = new FileOutputStream(new File(sDestinationPath));
googleDriveService.files().get(sFileId).executeAndDownloadTo(oFileOutputStream);
oFileOutputStream.close();
return true;
} catch (IOException e) {
return false;
}
}
文件被上传(显然)但是,当我下载它时,它不可读。尺寸也小了很多。我需要上传图像和其他文件,例如我自己的应用程序设置(不是 mime 类型),这就是我在此行中设置 null 的原因:
FileContent mediaContent = new FileContent(null,filePath);
我也尝试过“image/jpeg”,但得到了相同的结果。下载的文件不可读。
对我做错了什么有任何想法吗?我找不到太多关于 Google Drive v3 和 Android with Java 的文档。
解决方法
好的,解决了。问题出在 DownloadFileFromGoogleDrive 函数中:
boolean DownloadFileFromGoogleDrive(String sFileId,String sDestinationPath) {
try {
OutputStream oOutputStream = new FileOutputStream(sDestinationPath);
googleDriveService.files().get(sFileId).executeMediaAndDownloadTo(oOutputStream);
oOutputStream.flush();
oOutputStream.close();
return true
} catch (IOException e) {
return false;
}
}