I'm trying to upload a file to Google drive using outputstream
. With download I was able to get the InputStream
this way:
public void downloadStarted() throws Exception
{
HttpResponse resp = drive.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute();
serverInputStream = resp.getContent();
}
For the upload I have this sample test that is working:
private static File uploadFile(boolean useDirectUpload) throws IOException
{
File fileMetadata = new File();
fileMetadata.setTitle(UPLOAD_FILE.getName());
FileContent mediaContent = new FileContent("*/*", UPLOAD_FILE);
Drive.Files.Insert insert = drive.files().insert(fileMetadata, mediaContent);
MediaHttpUploader uploader = insert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(useDirectUpload);
uploader.setProgressListener(new FileUploadProgressListener());
return insert.execute();
}
but I really need the outputstream
and have no idea how to get it. Any help?
I think it's not possible to directly write the OutputStream
with the Google Drive HTTP API. The Drive.Files.create()
and insert()
accepts an AbstractInputStreamContent
, so it has to be an InputStream
. A workaround would be something like this:
ByteArrayOutputStream out = new ByteArrayOutputStream();
// use out
File file = drive.files().create(fileMetadata, new ByteArrayContent("",
out.toByteArray())).setFields("id").execute();
Another idea that might work is to use PipedInputStream
/ PipedOutputStream
. Place the drive.files().create(fileMetadata, pipedInputstream).setFields(id").execute()
inside a Thread
so that it will not block.
i don't prefer pipe because of bad performance.
but this is somehow tricky ;-P
the api forces us to use AbstractInputStreamContent
, but in my code InputStream
is never called.
com.google.apis::google-api-services-drive:v3-rev12-1.21.0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.