目录
  • 前言
  • 一、单文件上传
    • 1、apiService中
    • 2、acivity代码
  • 二、多文件上传
    •  1、apiservice中
    • 2、acivity代码
  • 总结

    Android 使用 okhttp3和retrofit2 进行单文件和多文件上传

    前言

    开发项目中需要进行单文件多文件的上传功能,下面演示的ApiResponse是自己分装的返回值,要根据自己的项目来完成。使用的mvvm框架,kotlin协程。

    看下大体思路和传参形式,仅供参考

    一、单文件上传

    1、apiService中

         @Multipart
        @POST("xxxx/xxx")
        suspend fun upload(
            @Part part: MultipartBody.Part,
            @Query("code") code: String
        ): ApiResponse<String>

    2、acivity代码

      val file = File(it)
      val requestBody: RequestBody = RequestBody.create(MediaType.parse("image/*"), file)
     
      val part = MultipartBody.Part.createFormData("file", file.getName(), requestBody)
     
      mViewModel.upload(part)

    二、多文件上传

     1、apiservice中

        @POST("xxx/xxxxs")
        suspend fun uploads(
            @Body part: MultipartBody,
            @Query("code") code: String
        ): ApiResponse<String>

    2、acivity代码

          val builder = MultipartBody.Builder()
                builder.setType(MultipartBody.FORM)
                 getDataList()?.filter { !it.filePath.isNullOrEmpty() }.forEach {
                    val file = File(it.filePath)
                    builder.addFormDataPart(
                        "files",
                        file.getName(),
                        RequestBody.create(MediaType.parse("image/jpg"), file)
                    )
                }
     
                mViewModel.uploads(builder.build())

    总结

     记录总结,要根据自己的框架进行参考改造。

    声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。