Android Retrofit Coroutine 實現多圖片/檔案上傳功能
文章目錄
- 網路權限&導入Library
- 創建API的interface
- 創建RetrofitUtil
- 創建RetrofitHttpUpload(可方便用於添加key與value)
- 程式碼範例
1.網路權限&導入Library
Manifest
<uses-permission android:name="android.permission.INTERNET"/>
Gradle(Module)
dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.3'
}
2.創建API的interface
ApiService
@JvmSuppressWildcards
interface ApiService {
    @Multipart
    @POST("insert_image.php")
    suspend fun uploadImg(@PartMap params: Map<String, RequestBody>) : HttpResult
}
HttpResult
data class HttpResult(val status: String, val userMessage: String)
3.創建RetrofitUtil
class RetrofitUtils {
    private var retrofit: Retrofit = Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create())
        .client(getClient())
        .baseUrl("https://aa/bb/")
        .build()
    companion object {
        val instance: RetrofitUtils by lazy { RetrofitUtils() }
    }
    fun <T> getService(clazz: Class<T>): T {
        return retrofit.create(clazz)
    }
    private fun getClient(): OkHttpClient {
        val builder = OkHttpClient.Builder()
        val logInterceptor = HttpLoggingInterceptor()
        logInterceptor.level = HttpLoggingInterceptor.Level.BODY
        builder.addInterceptor(logInterceptor)
        return builder.build()
    }
}
4.創建RetrofitHttpUpload(可方便用於添加key與value)
class RetrofitHttpUpload {
    private val params = mutableMapOf<String, RequestBody>()
    fun addParameter(key: String, o: Any): RetrofitHttpUpload {
        if (o is String) {
            val body = RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), o)
            params[key] = body
        } else if (o is File) {
            val body = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), o)
            params[key + "\"; filename=\"" + o.name] = body
        }
        return this
    }
    fun builder() = params
}
5.程式碼範例
//取得圖片檔案
val bitmap = BitmapFactory.decodeResource(resources, R.drawable.girl)
val file = File(externalCacheDir, "girl.jpg")
val ops = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ops)
ops.close()
//將資料加入RequestBody
val params = RetrofitHttpUpload().addParameter("file", file).builder()
CoroutineScope(Dispatchers.IO).launch {
    val httpResult = RetrofitUtils.instance.getService(ApiService::class.java).uploadImg(params)
    Log.e("GGG", httpResult.userMessage)
}
