How to upload files using Retrofit in Kotlin Android
How to upload files using Retrofit in Kotlin Android.
How to Upload Files Using Retrofit in Kotlin Android
In this tutorial, we will learn how to upload files using Retrofit in a Kotlin Android application. Retrofit is a popular networking library that makes it easy to interact with APIs in Android applications.
Step 1: Add Dependencies
First, make sure you have Retrofit added to your project. Open your app-level build.gradle
file and add the following dependencies:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
Step 2: Create a Retrofit Service Interface
Next, we need to create a service interface that defines the API endpoints for file upload. Create a new Kotlin file called ApiService.kt
and add the following code:
interface ApiService {
@Multipart
@POST("upload")
suspend fun uploadFile(
@Part file: MultipartBody.Part
): Response<UploadResponse>
}
In this example, we have a single endpoint called upload
which accepts a file as a MultipartBody.Part
parameter. The response is wrapped in a Response
object, and we expect an UploadResponse
object as the response body.
Step 3: Create the Retrofit Instance
We need to create a Retrofit instance that will be used to make API calls. Create a new Kotlin file called ApiClient.kt
and add the following code:
object ApiClient {
private const val BASE_URL = "https://example.com/"
private val retrofit: Retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val apiService: ApiService by lazy {
retrofit.create(ApiService::class.java)
}
}
In this example, we use a singleton pattern to create a Retrofit instance with the base URL and the Gson converter factory.
Step 4: Create a File Upload Function
Now, let's create a function in our activity or fragment that handles file upload. Add the following code to your activity/fragment:
private fun uploadFile(file: File) {
val requestFile = RequestBody.create(MediaType.parse("image/*"), file)
val body = MultipartBody.Part.createFormData("file", file.name, requestFile)
val call = ApiClient.apiService.uploadFile(body)
call.enqueue(object : Callback<UploadResponse> {
override fun onResponse(
call: Call<UploadResponse>,
response: Response<UploadResponse>
) {
if (response.isSuccessful) {
val uploadResponse = response.body()
// Handle successful upload response
} else {
// Handle error response
}
}
override fun onFailure(call: Call<UploadResponse>, t: Throwable) {
// Handle network error
}
})
}
In this example, we create a RequestBody
from the file and then create a MultipartBody.Part
from the RequestBody
. We pass this part to the uploadFile
function in the Retrofit service interface.
We use enqueue
to make the API call asynchronously and handle the response using the Callback
interface.
Step 5: Request File Permission (Optional)
If you are targeting Android 6.0 (API level 23) or higher, you need to request the file permission at runtime. Add the following code to your activity/fragment to request the file permission:
private fun requestFilePermission() {
val permission = Manifest.permission.READ_EXTERNAL_STORAGE
val requestCode = 123
if (ContextCompat.checkSelfPermission(this, permission)
!= PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(this, arrayOf(permission), requestCode)
} else {
// Permission already granted
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
if (requestCode == 123 && grantResults.isNotEmpty()
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
) {
// Permission granted
} else {
// Permission denied
}
}
Step 6: Trigger File Upload
Finally, you can trigger the file upload by calling the uploadFile
function with the file you want to upload. Here's an example of how to do it:
val file = File("/path/to/file")
uploadFile(file)
Make sure to replace /path/to/file
with the actual file path.
That's it! Now you know how to upload files using Retrofit in a Kotlin Android application. You can customize the code according to your specific requirements and API endpoints.
Remember to handle error cases and provide appropriate error handling in your application.