【问题标题】:How to POST a large file (> 5 mb) from Blobstore to Google Drive?如何将大文件(> 5 mb)从 Blobstore 发布到 Google Drive?
【发布时间】:2012-06-26 11:25:03
【问题描述】:

我的 Blobstore 中存储了 Blob,并希望将这些文件推送到 Google 云端硬盘。 当我使用 Google App Engine UrlFetchService 时

URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
URL url = new URL("https://www.googleapis.com/upload/drive/v1/files");
HTTPRequest httpRequest = new HTTPRequest(url, HTTPMethod.POST);
httpRequest.addHeader(new HTTPHeader("Content-Type", contentType));
httpRequest.addHeader(new HTTPHeader("Authorization", "OAuth " + accessToken));
httpRequest.setPayload(buffer.array());
Future<HTTPResponse> future = fetcher.fetchAsync(httpRequest);
try {
  HTTPResponse response = (HTTPResponse) future.get();
} catch (Exception e) {
  log.warning(e.getMessage());
}

问题:当文件超过5mb时,超过了UrlFetchService请求大小的限制(链接:https://developers.google.com/appengine/docs/java/urlfetch/overview#Quotas_and_Limits)

替代方案:使用 Google Drive API 我有以下代码:

File body = new File();
body.setTitle(title);
body.setDescription(description);
body.setMimeType(mimeType);

// File's content.
java.io.File fileContent = new java.io.File(filename);
FileContent mediaContent = new FileContent(mimeType, fileContent);

File file = service.files().insert(body, mediaContent).execute();

此解决方案的问题: Google App Engine 不支持 FileOutputStream 来管理从 Blobstore 读取的 byte[]。

有什么想法吗?

【问题讨论】:

    标签: java google-app-engine blobstore google-drive-api


    【解决方案1】:

    为此,请使用小于 5 兆字节的块的可恢复上传。这在 Google API Java Client for Drive 中很容易做到。这是一个改编自您已经提供的云端硬盘代码的代码示例。

    File body = new File();
    body.setTitle(title);
    body.setDescription(description);
    body.setMimeType(mimeType);
    
    java.io.File fileContent = new java.io.File(filename);
    FileContent mediaContent = new FileContent(mimeType, fileContent);
    
    Drive.Files.Insert insert = drive.files().insert(body, mediaContent);
    insert.getMediaHttpUploader().setChunkSize(1024 * 1024);
    File file = insert.execute();
    

    有关更多信息,请参阅相关类的 javadocs:

    【讨论】:

    • 感谢您调整我的云端硬盘代码。我通过利用可恢复上传来更新我的应用程序。将此代码上传到 Google App Engine 后,我得到 java.lang.NoSuchMethodError: com.google.api.services.drive.Drive$Files$Insert.getMediaHttpUploader()Lcom/google/api/client/googleapis/MediaHttpUploader;我需要对此进行更多研究......
    • 你有哪个版本的 google-api-java-client?是最新的吗?见这里:code.google.com/p/google-api-java-client
    • 谢谢维克!更新所有使用的 API 库后,您提供的代码运行良好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    • 2021-02-24
    • 2015-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多