POST Multipart Form Data using Retrofit 2.0 including image

前端 未结 10 1797
名媛妹妹
名媛妹妹 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:50

    Adding to the answer given by @insomniac. You can create a Map to put the parameter for RequestBody including image.

    Code for Interface

    public interface ApiInterface {
    @Multipart
    @POST("/api/Accounts/editaccount")
    Call editUser (@Header("Authorization") String authorization, @PartMap Map map);
    }
    

    Code for Java class

    File file = new File(imageUri.getPath());
    RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
    RequestBody name = RequestBody.create(MediaType.parse("text/plain"), firstNameField.getText().toString());
    RequestBody id = RequestBody.create(MediaType.parse("text/plain"), AZUtils.getUserId(this));
    
    Map map = new HashMap<>();
    map.put("file\"; filename=\"pp.png\" ", fbody);
    map.put("FirstName", name);
    map.put("Id", id);
    Call call = client.editUser(AZUtils.getToken(this), map);
    call.enqueue(new Callback() {
    @Override
    public void onResponse(retrofit.Response response, Retrofit retrofit) 
    {
        AZUtils.printObject(response.body());
    }
    
    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
     }
    });
    

提交回复
热议问题