使用Retrofit上传图片

Retrofit使用协程发送请求参考文章 :https://www.cnblogs.com/sw-code/p/14451921.html

导入依赖

app的build文件中加入:

implementation ‘com.squareup.retrofit2:retrofit:2.9.0‘
implementation ‘com.squareup.retrofit2:converter-gson:2.9.0‘
  • 注意依赖版本

Retrofit实例

/**
 * 创建Retrofit提供API Service
 */
object RetrofitClient {

    const val BASE_URL = "http://192.168.2.194:8080/" // http://localhost:8080/

    val okHttpClient = OkHttpClient.Builder()
        .callTimeout(30, TimeUnit.SECONDS)
        .build()

    val retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(okHttpClient)
        .build()

    val articleService = retrofit.create(ArticleService::class.java)

}

Service

interface ArticleService {
    @Multipart
    @POST("article/upload/picture")
    suspend fun uploadSingle(@Part file: MultipartBody.Part): ResultData<Picture>
    
    @Multipart
    @POST("article/upload/pictures")
    suspend fun uploadMulti(@Part files: List<MultipartBody.Part>): ResultData<Picture>
}
  • 注意,请求路径前不加/,因为BASE_URL中已经加了

在ViewModel中使用

class ArticleViewModel : ViewModel() {

    val picture by lazy {
        MutableLiveData<Picture>()
    }
    
    /**
     * 上传单张图片
     */
    fun uploadSinglePicture(file: File) {
        val builder = MultipartBody.Builder().setType(MultipartBody.FORM) //表单类型
        val requestFile: RequestBody = RequestBody.create(MediaType.parse("image/*"), file)
        builder.addFormDataPart("file", file.name, requestFile)
        val part = builder.build().part(0)
        viewModelScope.launch {
            val resultData = RetrofitClient.articleService.uploadSingle(part)
            picture.value = resultData.data
        }
    }
    
    /**
     * 上传多张图片
     */
    fun uploadSinglePicture(files: List<File>) {
        val builder = MultipartBody.Builder().setType(MultipartBody.FORM) //表单类型
        for (file in files) {
            val requestFile: RequestBody = RequestBody.create(MediaType.parse("image/*"), file)
            builder.addFormDataPart("file", file.name, requestFile)
        }
        val parts = builder.build().parts()
        viewModelScope.launch {
            val resultData = RetrofitClient.articleService.uploadMulti(parts)
            picture.value = resultData.data
        }
    }
}

SpringBoot项目接收

/**
 * 接收单张图片
 */
@PostMapping("upload/picture")
public Map<String, Object> uploadPicture(@RequestParam("file") MultipartFile file) {
    System.out.println(file.getOriginalFilename());
    Map<String, Object> dataMap = new HashMap<>();
    dataMap.put("url", "http://localhost:8080/picture/" + file.getOriginalFilename());
    return dataMap;
}

额外参数

这个直接添加就行了.................

使用Retrofit上传图片

上一篇:vue项目中引用spreadjs方法


下一篇:《数学建模:基于R》——2.1 回归分析