v3中的Google云端硬盘可恢复上传

时间:2019-08-18 10:49:37

标签: java android google-drive-api

我正在寻找一些帮助/示例,以使用Java中新的v3 REST API执行可恢复的上传到Google云端硬盘。

我知道这里有一个低级描述:Upload files | Google Drive API。但是目前,我不愿意理解这些低级请求中的任何一个,如果没有另一个更简单的方法(如以前的MediaHttpUploader,现在已弃用...)

我目前要做的是:

    File fileMetadata = new File();
    fileMetadata.setName(name);
    fileMetadata.setDescription(...);
    fileMetadata.setParents(parents);
    fileMetadata.setProperties(...);
    FileContent mediaContent = new FileContent(..., file);
    drive.files().create(fileMetadata, mediaContent).execute();

但是对于大文件,如果连接中断,这不是很好。

1 个答案:

答案 0 :(得分:1)

我最近刚刚在上面创建了一个实现。它将在您的DriveFolder上创建一个新文件,并在任务成功后返回其元数据。上载时,它还将使用上载信息更新侦听器。我添加了注释以使其可自动解释:

public Task<File> createFile(java.io.File yourfile, MediaHttpUploaderProgressListener uploadListener) {
        return Tasks.call(mExecutor, () -> {
            //Generates an input stream with your file content to be uploaded
            FileContent mediaContent = new FileContent("yourFileMimeType", yourfile);
            //Creates an empty Drive file           
            File metadata = new File() 
                    .setParents(parents) 
                    .setMimeType(yourFileMimeType)
                    .setName(yourFileName);

            //Builds up the upload request
            Drive.Files.Create uploadFile = mDriveService.files().create(metadata, mediaContent);
            //This will handle the resumable upload
            MediaHttpUploader uploader = uploadBackup.getMediaHttpUploader();
            //choose your chunk size and it will automatically divide parts
            uploader.setChunkSize(MediaHttpUploader.MINIMUM_CHUNK_SIZE); 
            //according to Google, this enables gzip in future (optional)
            uploader.setDisableGZipContent(false);  versions
            //important, this enables resumable upload
            uploader.setDirectUploadEnabled(false); 
            //listener to be updated
            uploader.setProgressListener(uploadListener);

            return uploadFile.execute();
        });
    }

并使您的Activity扩展MediaHttpUploaderProgressListener,以便实时更新文件进度:

@Override
public void progressChanged(MediaHttpUploader uploader) {
    String sizeTemp = "Uploading"
            + ": "
            + Formatter.formatShortFileSize(this, uploader.getNumBytesUploaded())
            + "/"
            + Formatter.formatShortFileSize(this, totalFileSize);
    runOnUiThread(() -> textView.setText(sizeTemp));
}

要计算进度百分比,只需执行以下操作:

double percentage = uploader.getNumBytesUploaded() / totalFileSize

或使用此一个:

uploader.getProgress()

它为您提供了已上载的字节百分比,介于0.0(0%)和1.0(100%)之间。但是请确保指定您的内容长度,否则它将抛出IllegalArgumentException