可恢复上传 - Google云端硬盘

时间:2017-03-14 12:10:05

标签: java google-drive-api

您好我试图通过google drive API实施Resumable Upload,但我遇到了问题。

是否有人能够从谷歌的tutorial运行上述代码?

File mediaFile = new File("/tmp/Test.jpg");
InputStreamContent mediaContent =
    new InputStreamContent("image/jpeg",
        new BufferedInputStream(new FileInputStream(mediaFile)));
mediaContent.setLength(mediaFile.length());

MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, transport, httpRequestInitializer);
uploader.setProgressListener(new CustomProgressListener());
HttpResponse response = uploader.upload(requestUrl);
if (!response.isSuccessStatusCode()) {
  throw GoogleJsonResponseException(jsonFactory, response);
}

我需要知道如何声明/创建传输变量和 httpRequestInitializer

或者将文件大量上传到Google系统的示例。

1 个答案:

答案 0 :(得分:0)

HttpRequestInitializerBasic Authentication Scheme中指定的基本身份验证HTTP请求初始值设定项。

例如,这可能用于禁用请求超时:

public class DisableTimeout implements HttpRequestInitializer {
  public void initialize(HttpRequest request) {
    request.setConnectTimeout(0);
    request.setReadTimeout(0);
  }
}

正如您所说,您需要使用resumable media upload上传/发送大块文件块。例如,Drive APIinsert方法支持mediaUpload,您可以使用以下代码上传文件:

class CustomProgressListener implements MediaHttpUploaderProgressListener {
  public void progressChanged(MediaHttpUploader uploader) throws IOException {
    switch (uploader.getUploadState()) {
      case INITIATION_STARTED:
        System.out.println("Initiation has started!");
        break;
      case INITIATION_COMPLETE:
        System.out.println("Initiation is complete!");
        break;
      case MEDIA_IN_PROGRESS:
        System.out.println(uploader.getProgress());
        break;
      case MEDIA_COMPLETE:
        System.out.println("Upload is complete!");
    }
  }
}

File mediaFile = new File("/tmp/driveFile.jpg");
InputStreamContent mediaContent =
    new InputStreamContent("image/jpeg",
        new BufferedInputStream(new FileInputStream(mediaFile)));
mediaContent.setLength(mediaFile.length());

Drive.Files.Insert request = drive.files().insert(fileMetadata, mediaContent);
request.getMediaHttpUploader().setProgressListener(new CustomProgressListener());
request.execute();

以下是一些可能也有帮助的参考资料: