Upload Large Files To Google Drive Using Gd Api
I want to upload large files to Google Drive programmatically using the new Drive API for android. Could you please suggest me a tutorial with best practices for this? I was readin
Solution 1:
I've been using this quick start from Google as a starting point. It shows how to upload a Bitmap but it's easy to adapt. They also do save the whole thing in a byte array and write it to the output stream for Google Drive. If you don't want to do this then I would recommend doing something like this instead:
/**
* Create a new file and save it to Drive.
*/privatevoidsaveFileToDrive(final File file) {
// Start by creating a new contents, and setting a callback.
Log.i(TAG, "Creating new contents.");
Drive.DriveApi.newDriveContents(mGoogleApiClient)
.setResultCallback(newResultCallback<DriveApi.DriveContentsResult>() {
@OverridepublicvoidonResult(DriveApi.DriveContentsResult result) {
// If the operation was not successful, we cannot do anything// and must// fail.if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Failed to create new contents.");
return;
}
// Otherwise, we can write our data to the new contents.
Log.i(TAG, "New contents created.");
// Get an output stream for the contents.OutputStreamoutputStream= result.getDriveContents().getOutputStream();
// Write the bitmap data from it.try {
FileInputStreamfileInputStream=newFileInputStream(file);
byte[] buffer = newbyte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1)
{
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
// Create the initial metadata - MIME type and title.// Note that the user will be able to change the title later.MetadataChangeSetmetadataChangeSet=newMetadataChangeSet.Builder()
.setTitle(file.getName()).build();
// Create an intent for the file chooser, and start it.IntentSenderintentSender= Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialDriveContents(result.getDriveContents())
.build(mGoogleApiClient);
try {
startIntentSenderForResult(
intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
Log.i(TAG, "Failed to launch file chooser.");
}
}
});
}
With the setup from the quickstart you could use this method to upload your file.
Post a Comment for "Upload Large Files To Google Drive Using Gd Api"