简体   繁体   中英

How to upload a file to Google Drive

So im trying to upload a text file to my google drive from an android app I am creating. I learned how to upload a picture from the Google tutorial. Also, I will be using the strings from my app in the text file. Potentially, I want to make it a spreadsheet. Any help?

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."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM