Android:无法使用Retrofit 2.0.0 beta 2上传多部分图像文件

时间:2016-01-19 06:21:59

标签: android retrofit retrofit2

您好我无法使用改装2.0.0-beta2上传图片。 它让我"图像缺失"错误。虽然我检查了该文件存在于系统中,但是如果我在图像视图中显示它正确显示。

需要上传的网址 http://mywebsite.com/signature/upload/

所以我的BASE_URL = http://mywebsite.com/

我的 .gradle 文件包含:

compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
compile 'com.squareup.okhttp:logging-interceptor:2.6.0'

SeriveGenerator.java 类是

public class ServiceGenerator {

public static final String API_BASE_URL = Urls.URL_BASE;

private static OkHttpClient httpClient = new OkHttpClient();



private static Retrofit.Builder builder =
        new Retrofit.Builder()
                .baseUrl(API_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create());

public static <S> S createService(Class<S> serviceClass) {
    Retrofit retrofit = builder.client(httpClient).build();
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    httpClient.interceptors().add(interceptor);
    return retrofit.create(serviceClass);
}

}

UploadService.java 类是

public interface UploadService {
@Multipart
@POST("/signature/upload/")  
// Tried to change this to "/signature/upload" as well (no slash in end)
// then gives Method not allowed error"
Call<String> upload(
        @Part("image") RequestBody file,
        @Part("image_name") String name);
}

最后在我的android活动中

// photoFile is the file, checked that it exist in system and 
// path is also correct

public void uploadFileToServer() {
    UploadService service =
            ServiceGenerator.createService(UploadService.class);

    String name = "xyz.jpg";

    RequestBody requestBody =
            RequestBody.create(MediaType.parse("multipart/form-data"), photoFile);

    Call<String> call = service.upload(requestBody, name);
    call.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Response<String> response, Retrofit retrofit) {

            Log.v("Upload", "success");
        }

        @Override
        public void onFailure(Throwable t) {
            Log.e("Upload", t.getMessage());
        }
    });
}

所以我获得成功记录&#34;成功&#34;从活动但服务器文件不存在,使用Postman,我尝试手动上传表单数据中的图像,正确上传。

1 个答案:

答案 0 :(得分:1)

几天前我遇到了类似的问题。这是我的工作代码。

首先,您必须定义接口。不添加内容类型标头非常重要。 在下文中,您会看到@Part("picture\";&#34;图片&#34;是后端期望的相应名称(在我的例子中)。因此,您必须更改此名称才能使其与后端一起使用。文件名= \&#34;图像\&#34;只需定义上传图片的名称即可。 就我而言,该方法位于&#34; DiaryService.java&#34;。

    @Multipart
    @POST("signature/upload")
    public Call<Void> addImageElementToDiary(@Part("picture\"; filename=\"image\" ") RequestBody picture,
                                             @Part("sort") RequestBody sort);

现在您可以调用上面定义的服务。正确解析Mediatype非常重要。您使用了&#34; multipart / form-data&#34;,这在我的情况下不起作用。您应该查看以下Mediatypes。

    File file = new File(((CreateDiaryImage) element).getImagePath());

        RequestBody sort = RequestBody.create(MediaType.parse("text/plain"), element.getSort() + "");

        RequestBody requestBody =
                RequestBody.create(MediaType.parse("image/*"), file);

        Call<Void> call = diaryService.addImageElementToDiary(requestBody, sort);
        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Response<Void> response, Retrofit retrofit) {
                Log.v("Upload", "success");
            }

            @Override
            public void onFailure(Throwable t) {
                Log.e("Upload", t.getMessage());
            }
        });