'Upload file form uri using retrofit android with kotlin
I am trying to upload a video using retrofit, but I can't generate the correct format this is my postman request :
postman request: https://i.stack.imgur.com/rDC6s.png
and this is the API endpoint call :
@POST("uploadVideo")
suspend fun uploadVideo(@Body body: UploadVideoRequest) : Response<DefaultResponse>
,Also this the "UploadVideoRequest" class :
data class UploadVideoRequest(
@SerializedName("video")
val video: RequestBody? = null
)
finally this is my call :
fun createPostWithVideo(fileName: String) {
val file = File(fileName);
val requestFile = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), file)
val body = MultipartBody.Part.createFormData("video", requestFile.toString())
viewModel.uploadVideoRequest = UploadVideoRequest(
video = body.body,
)
viewModel.uploadVideo()
}
But I am still not able to send that request
Solution 1:[1]
The way you are trying to send the video is not correct. Please follow these steps to send a video using retrofit. First, create a network interface like this.
@Multipart
@POST("uploadVideo")
suspend fun uploadVideo(@Part part: MultipartBody.Part) : Response<DefaultResponse>
Second, call function like this:
fun createMultipartBodyPart(file: File) {
val requestBody = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), file)
val body = MultipartBody.Part.createFormData("name", file.name, requestBody)
service.uploadVideo(body)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yousef Kazemi |
