Error uploading a file using Retrofit 2

后端 未结 2 924
别那么骄傲
别那么骄傲 2021-02-20 17:04

I\'m trying to upload a file (picture) to the server using Retrofit 2. I\'m following that tutorial which seems pretty easy at first, but didn\'t work in my case...

相关标签:
2条回答
  • 2021-02-20 17:29

    The Exceptions says that the first @Part doesn't needs a name in the annotation.

    @Multipart
    @POST(Constants.URL_UPLOAD)
    Call<ResponseBody> upload(@Part RequestBody description,
                              @Part MultipartBody.Part file);
    
    0 讨论(0)
  • 2021-02-20 17:31

    I fix my issue using this link : https://github.com/square/retrofit/issues/1063#issuecomment-145920568

    This is the solution of the problem:

    @Multipart
    @POST ("/api/Events/editevent")
    Call<Event> editEvent (@PartMap Map<String, RequestBody> params);
    

    I call it by following way.

    Map<String, RequestBody> map = new HashMap<>();
    map.put("Id", AZUtils.toRequestBody(eventId));
    map.put("Name", AZUtils.toRequestBody(titleView.getValue()));
    
    if (imageUri != null) {
          File file = new File(imageUri.getPath());
          RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), file);
          map.put("file\"; filename=\"pp.png\"", fileBody);
    }
    
    Call<Event> call = api.editEvent(map);
    call.enqueue(new Callback<Event>() { }
    

    The method toRequestBody just converts String into RequestBody

    public static RequestBody toRequestBody (String value) {
        RequestBody body = RequestBody.create(MediaType.parse("text/plain"), value);
        return body ;
    }
    
    0 讨论(0)
提交回复
热议问题