jmrsilva
jmrsilva

Reputation: 11

Upload file to Google Drive using outputstream

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?

Upvotes: 1

Views: 1766

Answers (2)

umjammer
umjammer

Reputation: 1

i don't prefer pipe because of bad performance.

how about https://github.com/umjammer/vavi-apps-fuse/blob/4b3477f4eef50967ad73569f938caec968d96c3f/vavi-nio-file-googledrive/src/main/java/vavi/nio/file/googledrive/GoogleDriveFileSystemDriver.java#L175-L216

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

Upvotes: -2

jpllosa
jpllosa

Reputation: 2202

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.

Upvotes: 3

Related Questions