【问题标题】:How to upload and download files from Google Drive (using Rest Api v3)如何从 Google Drive 上传和下载文件(使用 Rest Api v3)
【发布时间】:2021-10-05 00:21:22
【问题描述】:

我正在使用以下 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 的文档。

【问题讨论】:

  • 了解您是否遇到文件上传问题、文件下载问题或两者兼而有之会很有用。先来看看上传。您确定文件上传正确吗?能否在云端硬盘应用或在线查看是否正常?
  • 我正在上传到 AppFolder,所以我无法从网站上查看它。
  • 对。因此,为了调试,将其上传到非 AppData 文件夹以检查逻辑。如果我没记错的话,我认为除了指定不同的目标文件夹之外,逻辑应该是相同的。
  • 您要上传/下载什么文件和 MIME 类型?您是否尝试使用"Try his API" 工具来构建请求?
  • 不,我没有。让我看一下。我正在上传不同的文件类型,例如 png 文件和我的 sqllite 数据库的副本。

标签: android google-drive-api google-drive-android-api


【解决方案1】:

好的,解决了。问题出在 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;
    }
}

【讨论】:

    猜你喜欢
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 2023-02-06
    • 2021-07-15
    • 1970-01-01
    相关资源
    最近更新 更多