【问题标题】:Android Google Drive Send/Create FiileAndroid Google Drive 发送/创建文件
【发布时间】:2019-12-29 16:20:11
【问题描述】:

谁能告诉我如何将文件从 Android 手机发送到 Google Drive 的简短示例?

或创建包含内容的新文件并发送到云端硬盘。

www 网站上的 Google 示例代码有错误或来自新 API,但示例应用使用旧 api..

Google 示例:

File fileMetadata = new File();
fileMetadata.setTitle("photo.jpg");
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveService.files().insert(fileMetadata, mediaContent)
        .setFields("id")
        .execute();

但是像 setTitle() 和 insert() 这样的方法不存在吗?

我的代码:

  HttpTransport transport = AndroidHttp.newCompatibleTransport();
            JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
            mService = new com.google.api.services.drive.Drive.Builder(
                    transport, jsonFactory, credential)
                    .setApplicationName("Drive API Android Quickstart")
                    .build();

mService.files().create(new File().setName("TITLE").setMimeType("text/csv")).execute();

这个创建文件名为 TITLE 和正确的 MimeType。

但是如何发送正常的 java.io.File 或如何为 drive.model.File 创建内容??

【问题讨论】:

    标签: java android file google-drive-api


    【解决方案1】:

    您的 sn-p 很接近,但它与 Google's example 之间存在一些差异:

    File fileMetadata = new File();
    fileMetadata.setName("config.json");
    fileMetadata.setParents(Collections.singletonList("appDataFolder"));
    java.io.File filePath = new java.io.File("files/config.json");
    FileContent mediaContent = new FileContent("application/json", filePath);
    File file = driveService.files().create(fileMetadata, mediaContent)
        .setFields("id")
        .execute();
    
    • 使用setName 而不是setTitle
    • 将文件的父级设置为appDataFolder
    • 使用driveService.files().create 而不是driveService.files().insert

    【讨论】:

    • 但他们没有在新样本 developers.google.com/drive/v3/web/quickstart/android 中使用 getGoogleApiClient() 或者我错了吗?我记得旧 Api 中的 getGoogleApiClient() 但现在想使用新的。
    • 看来您是对的,API 已更改。我会更新我的答案。
    • 差不多。在我的情况下,filePath 不存在/已创建。
    • java.io.File myFile = new java.io.File("/data/user/0/com.PACKAGE/files/config.json");有了这个文件存在。因此,经过一些额外的修改和您的帮助,我得到了我想要的。谢谢接受。
    【解决方案2】:

    在您的设备上安装 Google 云端硬盘应用。嗯,我想你已经有了。

    然后使用 Intent.ACTION_OPEN_DOCUMENT 让用户从驱动器中选择一个文件,然后您可以读取和写入。

    或使用 Intent.ACTION_CREATE_DOCUMENT 让用户在您可以将文件复制到的驱动器上创建一个文件名。

    【讨论】:

    • 用户不会与此交互。例如,用户只会在 EditTexts 中写入一些信息,然后我必须完成这些信息并将其以文件的形式发送到 Google Drive。
    【解决方案3】:

    你需要添加

        implementation 'com.google.apis:google-api-services-drive:v3-rev20191108-1.30.3'
    

    在你的 Gradle 中。然后在你的课上

    import com.google.api.services.drive.model.File;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多