Uploading video to Google Drive programmatically (Android API)

馋奶兔 提交于 2019-11-28 08:45:21

Without getting into much detail, just a few pointers:

Anything you want to upload (image, text, video,...) consists from

  1. creating a file
  2. setting metadata (title, MIME type, description,...)
  3. setting content (byte stream)

The demo you mention does it with an image (JPEG bytestream) and you need to do it with video. So, the changes you need to implement are:

  • replace the "image/jpeg" MIME type with the one you need for your video
  • copy your video stream (outputStream.write(bitmapStream.toByteArray())...)

to the content.

These are the only changes you need to make. Google Drive Android API doesn't care what is your content and metadata, it just grabs it a shoves it up to Google Drive.

In Google Drive, apps (web, android,...) read the metadata and content, and treat it accordingly.

So this my complete code how I achieved uploading a video. Steps:

  • Fetch video file from uri(as in my case).
  • Get the byte array from bytearray outputstream as mentioned in the code
  • write the byte array to the ouputStream
  • the api will upload the file in the background

public class UploadVideo extends AppCompatActivity {

DriveClient mDriveClient;
DriveResourceClient mDriveResourceClient;
GoogleSignInAccount googleSignInAccount;
String TAG = "Drive";
private final int REQUEST_CODE_CREATOR = 2013;
Task<DriveContents> createContentsTask;
String uri;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload_video);
    //Fetching uri or path from previous activity.
    uri = getIntent().getStringExtra("uriVideo");
    //Get previously signed in account.
    googleSignInAccount = GoogleSignIn.getLastSignedInAccount(this);
    if (googleSignInAccount != null) {
        mDriveClient = Drive.getDriveClient(getApplicationContext(), googleSignInAccount);
        mDriveResourceClient =
                Drive.getDriveResourceClient(getApplicationContext(), googleSignInAccount);
    }
    else Toast.makeText(this, "Login again and retry", Toast.LENGTH_SHORT).show();
    createContentsTask = mDriveResourceClient.createContents();
    findViewById(R.id.uploadVideo).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
                createFile();
        }
    });
}

private void createFile() {
    // [START create_file]
    final Task<DriveFolder> rootFolderTask = mDriveResourceClient.getRootFolder();
    final Task<DriveContents> createContentsTask = mDriveResourceClient.createContents();
    Tasks.whenAll(rootFolderTask, createContentsTask)
            .continueWithTask(new Continuation<Void, Task<DriveFile>>() {
                @Override
                public Task<DriveFile> then(@NonNull Task<Void> task) throws Exception {
                    DriveFolder parent = rootFolderTask.getResult();
                    DriveContents contents = createContentsTask.getResult();
                    File file = new File(uri);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte[] buf = new byte[1024];
                    FileInputStream fis = new FileInputStream(file);
                    for (int readNum; (readNum = fis.read(buf)) != -1;) {
                        baos.write(buf, 0, readNum);
                    }
                    OutputStream outputStream = contents.getOutputStream();
                    outputStream.write(baos.toByteArray());

                    MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                            .setTitle("MyVideo.mp4") // Provide you video name here
                            .setMimeType("video/mp4") // Provide you video type here
                            .build();

                    return mDriveResourceClient.createFile(parent, changeSet, contents);
                }
            })
            .addOnSuccessListener(this,
                    new OnSuccessListener<DriveFile>() {
                        @Override
                        public void onSuccess(DriveFile driveFile) {
                            Toast.makeText(Upload.this, "Upload Started", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    })
            .addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.e(TAG, "Unable to create file", e);
                    finish();
                }
            });
    // [END create_file]
}

}

If you want to upload any file to Google Drive, then use the below code with Synchronization task, it will upload your file to Drive.

AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() 
                {
            @Override
            protected String doInBackground(Void... params) 
            {
               String file_type="video/mp4"; //write your file type
               File body = new File();                   
               File FileRtr = null;
               body.setTitle(myfile.getName());
               body.setMimeType(file_type);
               body.setParents(Arrays.asList(new ParentReference().setId(LocationID))); //LocationID means the path in the drive e where you want to upload it
            try 
            {
              FileContent mediaContent = new FileContent(file_type, myfile);
              FileRtr = mService.files().insert(body, mediaContent).execute();

              if ( FileRtr != null) 
              {
                System.out.println("File uploaded: " +  FileRtr.getTitle());

              }
              }
                catch (IOException e) 
                {
                 System.out.println("An error occurred: " + e.getMessage());
                }
                return null;

            } 
            protected void onPostExecute(String token) 
            {
             Toast.makeText(mContext, "Uploaded Successfuly",Toast.LENGTH_LONG).show();
            } 
            };
        task.execute();     

Solution by OP.

Thanks to seanpj, turns out I was overestimating the difficulty of this, I now use this method to upload both images and videos:

/**
 * Create a new file and save it to Drive.
 */
private void saveFiletoDrive(final File file, final String mime) {
    // Start by creating a new contents, and setting a callback.
    Drive.DriveApi.newDriveContents(mDriveClient).setResultCallback(
            new ResultCallback<DriveContentsResult>() {
                @Override
                public void onResult(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;
                    }
                     Log.i(TAG, "Connection successful, creating new contents...");
                    // Otherwise, we can write our data to the new contents.
                    // Get an output stream for the contents.
                    OutputStream outputStream = result.getDriveContents()
                            .getOutputStream();
                    FileInputStream fis;
                    try {
                        fis = new FileInputStream(file.getPath());
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buf = new byte[1024];
                        int n;
                        while (-1 != (n = fis.read(buf)))
                            baos.write(buf, 0, n);
                        byte[] photoBytes = baos.toByteArray();
                        outputStream.write(photoBytes);

                        outputStream.close();
                        outputStream = null;
                        fis.close();
                        fis = null;

                    } catch (FileNotFoundException e) {
                        Log.w(TAG, "FileNotFoundException: " + e.getMessage());
                    } catch (IOException e1) {
                        Log.w(TAG, "Unable to write file contents." + e1.getMessage());
                    }

                    String title = file.getName();
                    MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                            .setMimeType(mime).setTitle(title).build();

                    if (mime.equals(MIME_PHOTO)) {
                        if (VERBOSE)
                            Log.i(TAG, "Creating new photo on Drive (" + title
                                    + ")");
                        Drive.DriveApi.getFolder(mDriveClient,
                                mPicFolderDriveId).createFile(mDriveClient,
                                metadataChangeSet,
                                result.getDriveContents());
                    } else if (mime.equals(MIME_VIDEO)) {
                        Log.i(TAG, "Creating new video on Drive (" + title
                                + ")");
                        Drive.DriveApi.getFolder(mDriveClient,
                                mVidFolderDriveId).createFile(mDriveClient,
                                metadataChangeSet,
                                result.getDriveContents());
                    }

                    if (file.delete()) {
                        if (VERBOSE)
                            Log.d(TAG, "Deleted " + file.getName() + " from sdcard");
                    } else {
                        Log.w(TAG, "Failed to delete " + file.getName() + " from sdcard");
                    }
                }
            });
}
 private void saveFiletoDrive(final File file, final String mime) {
        Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(
                new ResultCallback<DriveContentsResult>() {

                    @Override
                    public void onResult(DriveContentsResult result) {

                        if (!result.getStatus().isSuccess()) {
                            Log.i(TAG, "Failed to create new contents.");
                            return;
                        }
                        Log.i(TAG, "Connection successful, creating new contents...");
                        OutputStream outputStream = result.getDriveContents()
                                .getOutputStream();
                        FileInputStream fis;
                        try {
                            fis = new FileInputStream(file.getPath());
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            byte[] buf = new byte[1024];
                            int n;
                            while (-1 != (n = fis.read(buf)))
                                baos.write(buf, 0, n);
                            byte[] photoBytes = baos.toByteArray();
                            outputStream.write(photoBytes);

                            outputStream.close();
                            outputStream = null;
                            fis.close();
                            fis = null;

                        } catch (FileNotFoundException e) {
                            Log.w(TAG, "FileNotFoundException: " + e.getMessage());
                        } catch (IOException e1) {
                            Log.w(TAG, "Unable to write file contents." + e1.getMessage());
                        }

                        String title = file.getName();
                        MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
                                .setMimeType(mime).setTitle(title).build();

                        if (mime.equals(MIME_PHOTO)) {
                            if (VERBOSE)
                                Log.i(TAG, "Creating new photo on Drive (" + title
                                        + ")");
                            Drive.DriveApi.getFolder(mGoogleApiClient,
                                    mPicFolderDriveId).createFile(mGoogleApiClient,
                                    metadataChangeSet,
                                    result.getDriveContents());
                        } else if (mime.equals(MIME_VIDEO)) {
                            Log.i(TAG, "Creating new video on Drive (" + title
                                    + ")");
                            Drive.DriveApi.getFolder(mGoogleApiClient,
                                    mVidFolderDriveId).createFile(mGoogleApiClient,
                                    metadataChangeSet,
                                    result.getDriveContents());
                        }

                        if (file.delete()) {
                            if (VERBOSE)
                                Log.d(TAG, "Deleted " + file.getName() + " from sdcard");
                        } else {
                            Log.w(TAG, "Failed to `enter code here`delete " + file.getName() + " from sdcard");
                        }
                    }
                });
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!