file is not upload using retrofit in kotlin
Using Retrofit to Upload a File in Kotlin
Add Internet Permission to Manifest File:
xml <uses-permission android:name="android.permission.INTERNET" />
Add Dependencies to build.gradle File:
gradle implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' implementation 'com.squareup.okhttp3:logging-interceptor:4.9.1'
Create a Service Interface:
kotlin interface FileUploadService { @Multipart @POST("upload") fun uploadFile( @Part file: MultipartBody.Part ): Call<ResponseBody> }
Create a Retrofit Instance:
kotlin val retrofit = Retrofit.Builder() .baseUrl("http://your-base-url.com/") .addConverterFactory(GsonConverterFactory.create()) .client(OkHttpClient.Builder() .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) .build() ) .build() val service = retrofit.create(FileUploadService::class.java)
Create a File Part and Call the API: ```kotlin val file = File("path-to-your-file") val requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file) val body = MultipartBody.Part.createFormData("file", file.name, requestFile)
val call = service.uploadFile(body)
call.enqueue(object : Callback
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
// Handle failure
}
}) ```