POST Multipart Form Data using Retrofit 2.0 including image

前端 未结 10 1633
名媛妹妹
名媛妹妹 2020-11-22 11:07

I am trying to do a HTTP POST to server using Retrofit 2.0

MediaType MEDIA_TYPE_TEXT = MediaType.parse(\"text/plain\");
MediaType MEDIA_TYPE         


        
10条回答
  •  忘了有多久
    2020-11-22 11:49

    There is a correct way of uploading a file with its name with Retrofit 2, without any hack:

    Define API interface:

    @Multipart
    @POST("uploadAttachment")
    Call uploadAttachment(@Part MultipartBody.Part filePart); 
                                       // You can add other parameters too
    

    Upload file like this:

    File file = // initialize file here
    
    MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
    
    Call call = api.uploadAttachment(filePart);
    

    This demonstrates only file uploading, you can also add other parameters in the same method with @Part annotation.

提交回复
热议问题