【问题标题】:Java Google Api [Service account]Java Google Api [服务帐号]
【发布时间】:2015-06-28 06:49:25
【问题描述】:

我无法将文件上传到特定的驱动器文件夹。

我的 Java 代码是:

HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    try {
        GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory).setServiceAccountId(IRingeeConstants.SERVICE_ACCOUNT_EMAIL)
                .setServiceAccountScopes(Collections.singleton(DriveScopes.DRIVE_APPDATA)).setServiceAccountPrivateKeyFromP12File(new java.io.File("G:\\Ringee-1a1f1b786226.p12")).build();

        Drive service = new Drive.Builder(httpTransport, jsonFactory, credential).setApplicationName(IRingeeConstants.APPLICATION_NAME).build();

        File body = new File();
        body.setTitle("ringee");
        body.setDescription("ringeeapp");
        body.setMimeType("application/vnd.google-apps.folder");
        java.io.File fileContent = new java.io.File("G:\\document.txt");
        FileContent mediaContent = new FileContent("text/plain", fileContent);

        File file = service.files().insert(body, mediaContent).execute();
        System.out.print("file id is :" + file.getId());
        Permission newPermission = new Permission();
        // for showing files in browser that reason only using additional
        // permission
        newPermission.setValue(IRingeeConstants.USER_ACCOUNT_EMAIL);
        newPermission.setType("owner");
        newPermission.setRole("writer");
        service.permissions().insert(file.getId(), newPermission).execute();
        getFileByFileId(service, file.getId());
    } catch (Exception e) {
        e.printStackTrace();
    }

文件上传到根文件夹。这是为什么呢?

如何解决这个问题..

【问题讨论】:

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


    【解决方案1】:

    这是一个code snippet get 在父目录中创建一个文件。可以通过名称、mime、...从search获取父目录ID

    我所指的Github example 有一个完整的 CRUD 包装器,用于 REST(您正在使用的那个)和 GDAA API。

    但请注意,在 Google Drive 中,文件/文件夹名称只是一个元数据字段。即您可能有多个同名的文件夹/文件在同一位置(文件夹)。只有 ID(有时称为资源 ID)是唯一的。这意味着如果您有一个文件夹名称并执行搜索,最好检查您是否只有一个对象 - 正确的对象(检查其父 ID、mime 类型......)。基本上你的全部逻辑都必须考虑在内。

    【讨论】:

      【解决方案2】:

      回答有点晚了,但如果您有可用的凭据,以下是一种将文件上传到 Google 云端硬盘的简单方法。获取授权的逻辑可以写在另一个函数中,在下面的例子中是authorize()。另外,我正在使用全局 Drive 实例,因为以下方法是其中之一。

      public static String insertFile(String folderId, java.io.File file) throws IOException, GeneralSecurityException {
          System.out.println("Uploading file " + file.getName() + " to Google Drive");
          HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      
          // authorization
          Credential credential = authorize(); // Get authorization
      
          // set up the global Drive instance
          drive = new Drive.Builder(httpTransport, JSON_FACTORY, credential)
                  .setApplicationName("YourAppName")
                  .build();
      
          File fileMetadata = new File();
          fileMetadata.setName(file.getName());
          FileContent mediaContent = new FileContent("put/mime/type/here", file);
      
          File uploadedFile;
          if (folderId != null && !folderId.isEmpty()) {
              fileMetadata.setParents(Collections.singletonList(folderId));
              uploadedFile = drive.files()
                      .create(fileMetadata, mediaContent)
                      .setFields("id, parents")
                      .execute();
          } else {
              uploadedFile = drive.files()
                      .create(fileMetadata, mediaContent)
                      .setFields("id")
                      .execute();
          }
      
          return uploadedFile == null ? null : uploadedFile.getId();
      }
      

      上述方法以folderId和要上传的文件为参数,上传成功则返回fileId

      如果您将null 或空字符串传递给folderId,则文件将上传到根目录。

      【讨论】:

        【解决方案3】:

        在 Google 驱动器中 Parents 是文件夹名称。

        默认情况下,文件放置在根目录中。如果您运行files.list 或在底部尝试它,您将获得 Google 驱动器上所有文件的列表。

        mimetype 为application/vnd.google-apps.folder 的文件是目录。

        {
        
           "kind": "drive#file",
           "id": "0B5pJkOVaKccEfjVaajNvRFNTa3pRZ2NlUmFWTjczaGpjaHE1NFo5bWFBWTJPOGU2TGtOTzA",     
           "title": "AppScripts",
           "mimeType": "application/vnd.google-apps.folder",
           "parents": [
            {    
             "kind": "drive#parentReference",
             "id": "0AJpJkOVaKccEUk9PVA",
        
             "parentLink": "https://www.googleapis.com/drive/v2/files/0AJpJkOVaKccEUk9PVA",
             "isRoot": true
            }
        

        在您的上方,您可以在我的 google 驱动器上看到我的 AppScripts 目录。如果你在 parents 下看到isRoot,你可以知道它在根目录中

          {
        
           "kind": "drive#file",
           "id": "0B1bbSFgVLpoXcEhfVDRFRF8tTkU",
           "title": "GDE-app-team",
           "mimeType": "application/vnd.google-apps.folder",
           "parents": [
            {
             "kind": "drive#parentReference",
             "id": "0B_UBp7FcUna-NU5abkhxYWVocTA",
             "selfLink": "https://www.googleapis.com/drive/v2/files/0B1bbSFgVLpoXcEhfVDRFRF8tTkU/parents/0B_UBp7FcUna-NU5abkhxYWVocTA",
             "parentLink": "https://www.googleapis.com/drive/v2/files/0B_UBp7FcUna-NU5abkhxYWVocTA",
             "isRoot": false
            }
        

        如果您注意到我的GDE-app-team 目录在上方,您发现它的 isRoot 设置为 false,那么它不在根目录中。它所在的目录是 0B_UBp7FcUna-NU5abkhxYWVocTA 我必须在该 id 上执行 files.get 才能找到 GDE-app-team 所在的目录的名称。

         "kind": "drive#file",
         "id": "0B_UBp7FcUna-NU5abkhxYWVocTA",
         "etag": "\"WsLEI6l9KW9DlzjU9lm9xLuMVm8/MTQwOTkyOTg4Njc0Mw\"",
         "selfLink": "https://www.googleapis.com/drive/v2/files/0B_UBp7FcUna-NU5abkhxYWVocTA",
         "alternateLink": "https://docs.google.com/folderview?id=0B_UBp7FcUna-NU5abkhxYWVocTA&usp=drivesdk",
         "iconLink": "https://ssl.gstatic.com/docs/doclist/images/icon_11_shared_collection_list_1.png",
         "title": "GDE",
        

        你需要给body添加父id

        parentId 可选父文件夹的 ID。

        我不是 java 专家,但从文档中看是这样的:

         body.setParents(Arrays.asList(new ParentReference().setId(parentId)));
        

        我通常用q 做一个文件列表来搜索所有目录

        mimeType = 'application/vnd.google-apps.folder'
        

        这应该会返回您需要添加到父母的文件 ID。

        【讨论】:

        • 感谢您的帮助..但我怀疑 parentId 是指文件夹名称还是 id。如果 id 表示如何从驱动器文件夹名称中获取 id?
        • 父 ID 确实意味着文件夹名称,这应该让您了解如何从驱动器获取信息。
        • 好的,我有文件夹名称如何获取此名称的 ID。
        • 但我们问题的答案仍然存在。将父 ID 添加到正文。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-13
        相关资源
        最近更新 更多