日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

Android?使用?okhttp3和retrofit2?進(jìn)行單文件和多文件上傳_Android

作者:_MWY ? 更新時(shí)間: 2022-12-02 編程語(yǔ)言

前言

開發(fā)項(xiàng)目中需要進(jìn)行單文件多文件的上傳功能,下面演示的ApiResponse是自己分裝的返回值,要根據(jù)自己的項(xiàng)目來(lái)完成。使用的mvvm框架,kotlin協(xié)程。

看下大體思路和傳參形式,僅供參考

一、單文件上傳

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

總結(jié)

?記錄總結(jié),要根據(jù)自己的框架進(jìn)行參考改造。

原文鏈接:https://blog.csdn.net/weixin_41620505/article/details/127534431

欄目分類
最近更新