How to upload a file to Google Drive

I spent so much time for that... In my opinion documentation is ..... not so great.

This is how it should be done with REST API v3. MULTIPART UPLOAD example

1. STEP ONE - Create JSON with METADATA

For example:

data class RetrofitMetadataPart(
    val parents: List<String>, //directories
    val name: String //file name
)

and now create a JSON (I used moshi for this)

val jsonAdapter = moshi.adapter<RetrofitMetadataPart>(RetrofitMetadataPart::class.java)

val metadataJSON = jsonAdapter.toJson(
    RetrofitMetadataPart(
        parents = listOf("yourFolderId"), 
        name = localFile.name
    )
)

of course you can create this metadata with different parameters,values, and of course in your preferred way. Full list of metadata parameters you have here: https://developers.google.com/drive/api/v3/reference/files/create

2. STEP TWO - Create Multipart with METADATA

We create first part of our request with proper Header

val metadataPart = MultipartBody.Part.create(
    RequestBody.create(MediaType.parse("application/json; charset=utf-8"), metadataJSON)
)

3. STEP THREE - Create Multipart with your FILE

Create second part of our request with file

val multimediaPart = MultipartBody.Part.create(
    RequestBody.create(MediaType.parse("image/jpeg"), localFile)
)

4. STEP FOUR - call request

googleDriveApi.uploadFileMultipart(
    metadataPart,
    multimediaPart
)

and this invoke

@Multipart
@POST("upload/drive/v3/files?uploadType=multipart")
fun uploadFileMultipart(
    @Part metadata: MultipartBody.Part,
    @Part fileMedia: MultipartBody.Part
): Completable

by sending this two Multiparts you get automatically those --foo_bar_baz marks from documentation

"Identify each part with a boundary string, preceded by two hyphens. In addition, add two hyphens after the final boundary string."


Read Quick Start on Google Android site.

When you are done with all the authentication process, go for How to upload file to Google Drive.

Edit

Reference Links

  • https://code.google.com/p/google-drive-sdk-samples/
  • Android Open and Save files to/from Google Drive SDK
  • http://mavenrepo.google-api-java-client.googlecode.com/hg/com/google/apis/google-api-services-drive/v2-rev9-1.8.0-beta/