Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST InputStream as the body of a request in Retrofit?

I'm attempting to do a POST with the body being an InputStream with something like this:

@POST("/build")
@Headers("Content-Type: application/tar")
Response build(@Query("t") String tag,
               @Query("q") boolean quiet,
               @Query("nocache") boolean nocache,
               @Body TypedInput inputStream);

In this case the InputStream is from a compressed tar file.

What's the proper way to POST an InputStream?

like image 263
digitalsanctum Avatar asked Mar 20 '14 18:03

digitalsanctum


1 Answers

You can upload inputStream using Multipart.

@Multipart
@POST("pictures")
suspend fun uploadPicture(
        @Part part: MultipartBody.Part
): NetworkPicture

Then in perhaps your repository class:

suspend fun upload(inputStream: InputStream) {
   val part = MultipartBody.Part.createFormData(
         "pic", "myPic", RequestBody.create(
              MediaType.parse("image/*"),
              inputStream.readBytes()
          )
   )
   uploadPicture(part)
}

If you want to find out how to get an image Uri, check this answer: https://stackoverflow.com/a/61592000/10030693

like image 172
Gilbert Avatar answered Sep 27 '22 17:09

Gilbert