Search code examples
androidgoogle-drive-android-api

How to upload files using the Google Drive API?


I'm trying to upload a file using the Google Drive api on Android

https://github.com/googlesamples/google-services/tree/master/android/signin/app/src/main/java/com/google/samples/quickstart/signin

I signed up to SignInActivityWithDrive.java in the link above.

But there is no example of uploading a file, downloading a file

I want to know how to upload and download files

Thank you


Solution

  • You can find basic examples of uploading and downloading in the docs.

    Uploading

    You can send upload requests in any of the following ways:

    • Simple upload: uploadType=media. For quick transfer of a small file (5 MB or less). To perform a simple upload, refer to Performing a Simple Upload.
    • Multipart upload: uploadType=multipart. For quick transfer of a small file (5 MB or less) and metadata describing the file, all in a single request. To perform a multipart upload, refer to Performing a Multipart Upload.
    • Resumable upload: uploadType=resumable. For more reliable transfer, especially important with large files. Resumable uploads are a good choice for most applications, since they also work for small files at the cost of one additional HTTP request per upload. To perform a resumable upload, refer to Performing a Resumable Upload.

    The following example shows how to upload an image using the client libraries:

    File fileMetadata = new File();
    fileMetadata.setName("photo.jpg");
    java.io.File filePath = new java.io.File("files/photo.jpg");
    FileContent mediaContent = new FileContent("image/jpeg", filePath);
    File file = driveService.files().create(fileMetadata, mediaContent)
        .setFields("id")
        .execute();
    System.out.println("File ID: " + file.getId());
    

    Downloading

    Depending on the type of download you'd like to perform — a file, a Google Document, or a content link — you'll use one of the following URLs:

    An example of a basic download is:

    String fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M";
    OutputStream outputStream = new ByteArrayOutputStream();
    driveService.files().get(fileId)
        .executeMediaAndDownloadTo(outputStream);