Google Drive V2 Java API - 将文件上传到特定文件夹

时间:2012-07-05 06:28:03

标签: google-drive-api

以下是使用Gdrive V2 sdk将文件上传到特定文件夹的方法。 1)将文件插入根文件夹(Drive.Files.insert(File,AbstractInputStream) 2)删除新上载文件的根父引用 3)将特定目标文件夹添加为文件的新父引用。

以上作品。 但是,如果网络速度很慢,我们会在移动到特定目标文件夹之前看到该文件位于Root文件夹中很长一段时间。我们怎能避免这种情况?我们可以批量上述所有三项业务吗?但AFAIK,批处理支持特定类型的操作,例如..我们只能批量所有文件操作或父操作或修订操作。我们可以批处理属于不同类型的操作,例如(Files.insert()和Parent.delete())吗?

输入将不胜感激。

谢谢!

2 个答案:

答案 0 :(得分:5)

您可以通过在元数据中设置父字段来直接在指定文件夹中创建文件。

{
  "title" : "test.jpg",
  "mimeType" : "image/jpeg",
  "parents": [{
    "kind": "drive#file",
    "id": "<folderId>"
  }]
}

这就是我在python中所做的,但我相信java中有相关内容。

答案 1 :(得分:1)

正如eric.f在答案中提到的,您需要为文件设置

来自https://developers.google.com/drive/v2/reference/files/insert

import com.google.api.client.http.FileContent;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;

import java.io.IOException;
import java.util.Arrays;
// ...

public class MyClass {

  // ...

  /**
   * Insert new file.
   *
   * @param service Drive API service instance.
   * @param title Title of the file to insert, including the extension.
   * @param description Description of the file to insert.
   * @param parentId Optional parent folder's ID.
   * @param mimeType MIME type of the file to insert.
   * @param filename Filename of the file to insert.
   * @return Inserted file metadata if successful, {@code null} otherwise.
   */
  private static File insertFile(Drive service, String title, String description,
      String parentId, String mimeType, String filename) {
    // File's metadata.
    File body = new File();
    body.setTitle(title);
    body.setDescription(description);
    body.setMimeType(mimeType);

    // Set the parent folder.
    if (parentId != null && parentId.length() > 0) {
      body.setParents(
          Arrays.asList(new ParentReference().setId(parentId)));
    }

    // File's content.
    java.io.File fileContent = new java.io.File(filename);
    FileContent mediaContent = new FileContent(mimeType, fileContent);
    try {
      File file = service.files().insert(body, mediaContent).execute();

      // Uncomment the following line to print the File ID.
      // System.out.println("File ID: %s" + file.getId());

      return file;
    } catch (IOException e) {
      System.out.println("An error occured: " + e);
      return null;
    }
  }

  // ...
}
相关问题