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())


总结

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

猜你喜欢

转载自blog.csdn.net/weixin_41620505/article/details/127534431