如何从Blobstore将大于5MB的文件POST到Google Drive?

7

我在Blobstore中存储了一些二进制大对象,希望将这些文件推送到Google Drive。当我使用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[]数组。 有什么想法吗?
1个回答

6
要实现这一点,使用小于5兆字节的可恢复上传块。在Google API Java Client for Drive中执行此操作非常简单。下面是从您已提供的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:


(注: jadavoc是Java程序员必备的开发文档,包含了各种Java类库、框架等的API说明和文档)

感谢您调整了我的Drive代码。我通过利用可恢复上传更新了我的应用程序。将此代码上传到Google应用引擎后,我收到以下错误:java.lang.NoSuchMethodError: com.google.api.services.drive.Drive$Files$Insert.getMediaHttpUploader()Lcom/google/api/client/googleapis/MediaHttpUploader;我需要再做一些研究... - Martin
你使用的是哪个版本的google-api-java-client?它是最新版吗?请参见此处: http://code.google.com/p/google-api-java-client/ - Vic Fryzel
谢谢Vic!在更新了所有使用的API库之后,你提供的代码完美运行! - Martin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接