How to partial download google drive files using j

2020-05-06 11:05发布

问题:

Using the sample code (Drive Java REST API V3) below, I am trying to download a portion of a file from google drive.

Drive.Revisions.Get get = service.revisions().get(fileId, revisionId)
            .setFields(FilterConstants.OBJECT_REVISION);

MediaHttpDownloader downloader = get.getMediaHttpDownloader();
downloader.setContentRange(fromByte, toByte);

inputStream = get.executeMediaAsInputStream();

But this is not working for me. Can someone help me how to resolve this issue?

回答1:

@Venkat, based on Partial download,

Partial download involves downloading only a specified portion of a file. You can specify the portion of the file you want to dowload by using a byte range with the Range header. For example:

Range: bytes=500-999

Sample:

GET https://www.googleapis.com/drive/v3/files/fileId
Range: bytes=500-999


回答2:

The following code works for me. The trick was to set Range header correctly

private byte[] getBytes(Drive drive, String downloadUrl, long position, int byteCount) {
    byte[] receivedByteArray = null;
    if (downloadUrl != null && downloadUrl.length() > 0) {
        try {
            com.google.api.client.http.HttpRequest httpRequestGet = drive.getRequestFactory().buildGetRequest(new GenericUrl(downloadUrl));
            httpRequestGet.getHeaders().setRange("bytes=" + position + "-" + (position + byteCount - 1));
            com.google.api.client.http.HttpResponse response = httpRequestGet.execute();
            InputStream is = response.getContent();
            receivedByteArray = IOUtils.toByteArray(is);
            response.disconnect();
            System.out.println("google-http-client-1.18.0-rc response: [" + position + ", " + (position + receivedByteArray.length - 1) + "]");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return receivedByteArray;
}