使用outputstream将文件上传到Google云端硬盘

时间:2016-03-21 13:15:04

标签: java google-drive-api

我正在尝试使用outputstream将文件上传到Google云端硬盘。通过下载,我可以通过这种方式获得InputStream

    public void downloadStarted() throws Exception 
    {
        HttpResponse resp = drive.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute();
       serverInputStream = resp.getContent();
    }

对于上传,我有一个正在运行的示例测试:

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();
}

但我真的需要outputstream并且不知道如何获得它。有什么帮助吗?

2 个答案:

答案 0 :(得分:1)

我认为无法使用Google Drive HTTP API直接编写OutputStreamDrive.Files.create()insert()接受AbstractInputStreamContent,因此必须为InputStream。解决方法是这样的:

ByteArrayOutputStream out = new ByteArrayOutputStream();
// use out
File file = drive.files().create(fileMetadata, new ByteArrayContent("", 
    out.toByteArray())).setFields("id").execute();

可能有用的另一个想法是使用PipedInputStream / PipedOutputStream。将drive.files().create(fileMetadata, pipedInputstream).setFields(id").execute()放在Thread内,以便它不会阻止。

答案 1 :(得分:-2)

由于性能不佳,我不喜欢管道。

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

但这有点棘手;-P

api强制我们使用AbstractInputStreamContent,但是在我的代码中 从未调用InputStream


com.google.apis :: google-api-services-drive:v3-rev12-1.21.0

相关问题