How to upload a file to Google Drive

后端 未结 2 1539
时光取名叫无心
时光取名叫无心 2020-12-05 05:44

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 th

2条回答
  •  执念已碎
    2020-12-05 06:27

    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, //directories
        val name: String //file name
    )
    

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

    val jsonAdapter = moshi.adapter(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."

提交回复
热议问题