软件编程
位置:首页>> 软件编程>> Android编程>> Android 使用 okhttp3和retrofit2 进行单文件和多文件上传

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

作者:_MWY  发布时间:2023-04-29 07:33:22 

标签:android,okhttp3,retrofit2,文件上传

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

来源:https://blog.csdn.net/weixin_41620505/article/details/127534431

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com