使用Retrofit 2上传文件时出错

时间:2016-04-15 17:22:33

标签: android retrofit retrofit2

我尝试使用Retrofit 2将文件(图片)上传到服务器。我跟着那个tutorial开始看起来很容易,但在我的情况下没有用......

当我调用API函数时,我总是收到此错误:

W/System.err: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
W/System.err:     at retrofit2.ServiceMethod$Builder.build(ServiceMethod.java:190)
W/System.err:     at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:166)
W/System.err:     at retrofit2.Retrofit$1.invoke(Retrofit.java:145)
W/System.err:     at java.lang.reflect.Proxy.invoke(Proxy.java:393)
W/System.err:     at com.plante.android.cobalt.fragment.FragmentIncidentPlan.uploadFile(FragmentIncidentPlan.java:575)

以下是我的API调用:

@Multipart
@POST(Constants.URL_UPLOAD)
Call<ResponseBody> upload(@Part RequestBody description,
                          @Part MultipartBody.Part file);

以下是我用来上传文件的方法:

private void uploadFile(String path) {
    // create upload service client

    // use the FileUtils to get the actual file by uri
    File file = new File(path);
    Log.e(TAG, file.getAbsolutePath());

    // create RequestBody instance from file
    RequestBody requestFile =
            RequestBody.create(MediaType.parse("multipart/form-data"), file);

    // MultipartBody.Part is used to send also the actual file name
    MultipartBody.Part body =
            MultipartBody.Part.createFormData("picture", file.getName(), requestFile);

    // add another part within the multipart request
    String descriptionString = "hello, this is description speaking";
    RequestBody description =
            RequestBody.create(
                    MediaType.parse("multipart/form-data"), descriptionString);

    // finally, execute the request
    Call<ResponseBody> call = cobaltServices.upload(description, body);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call,
                               Response<ResponseBody> response) {
            Log.v("Upload", "success");
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.e("Upload error:", t.getMessage());
        }
    });
}

2 个答案:

答案 0 :(得分:9)

例外说第一个@Part在注释中不需要名称。

@Multipart
@POST(Constants.URL_UPLOAD)
Call<ResponseBody> upload(@Part RequestBody description,
                          @Part MultipartBody.Part file);

答案 1 :(得分:9)

我使用此链接解决了我的问题:https://github.com/square/retrofit/issues/1063#issuecomment-145920568

这是问题的解决方案:

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

我按照以下方式打电话。

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>() { }

方法toRequestBody只是将String转换为RequestBody

public static RequestBody toRequestBody (String value) {
    RequestBody body = RequestBody.create(MediaType.parse("text/plain"), value);
    return body ;
}