Error uploading a file using Retrofit 2

后端 未结 2 927
别那么骄傲
别那么骄傲 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: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 editEvent (@PartMap Map params);
    

    I call it by following way.

    Map 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 call = api.editEvent(map);
    call.enqueue(new Callback() { }
    

    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 ;
    }
    

提交回复
热议问题