Google Drive InputStreamContent requires length to

2019-05-14 19:15发布

问题:

Examples of uploading a file to Google Drive typically use the FileContent class, this is easy to understand and works as expected.

In my current case, I only have an InputStream exposed, as the input may not necessarily originate from a file. I have tried to use the InputStreamContent class, however if the length is not set, an IllegalArgumentException is thrown:

Exception in thread "main" java.lang.IllegalArgumentException
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:72)
at com.google.api.client.googleapis.media.MediaHttpUploader.getMediaContentLength(MediaHttpUploader.java:315)
at com.google.api.client.googleapis.media.MediaHttpUploader.executeUploadInitiation(MediaHttpUploader.java:333)
at com.google.api.client.googleapis.media.MediaHttpUploader.upload(MediaHttpUploader.java:252)
at com.google.api.services.drive.Drive$Files$Insert.executeUnparsed(Drive.java:309)
at com.google.api.services.drive.Drive$Files$Insert.execute(Drive.java:331)

While I could copy the InputStream into a byte array perhaps and then obtain the size from that, it doesn't seem to be the most efficient approach. Is this the intended implementation? The javadoc does not indicate that the value needs to be set, which seems to be misleading:

/**
 * Sets the content length or less than zero if not known.
 *
 * <p>
 * Defaults to {@code -1}.
 * </p>
 *
 * @since 1.5
 */
public InputStreamContent setLength(long length) {
    this.length = length;
    return this;
}

回答1:

This is a known issue, details are here: http://code.google.com/p/google-api-java-client/issues/detail?id=591

We will get this fixed in the 1.12 google-api-java-client release.