Android Retrofit 2文件上传

时间:2016-03-15 14:04:32

标签: android file-upload retrofit2

我正在使用Retrofit 2,我想调用一个Web服务将我的图像上传到我的服务器。服务器端我使用Phalcon PHP并检查是否有要上传的文件。但我从来没有上传过的文件。我可以获取description参数但不能获取文件参数。

你能告诉我我的安卓代码是否正常?我不知道出了什么问题。

ApplicationService

public interface ApplicationService {

...
// My other web services works well

@Multipart
@POST("/path/to/uploadPictures")
Call<ResponseBody> upload(@Part("description") RequestBody description,
                          @Part("file") RequestBody file);

}

ServiceGenerator类

public class ServiceGenerator {

public static final String API_BASE_URL = Globals.SERVER_NAME;

private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

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()).build();
    return retrofit.create(serviceClass);
}

}

上传文件

private void uploadFile(String filename) {
    // create upload service client
    ApplicationService service = ServiceGenerator.createService(ApplicationService.class);

    File file = new File(this.getExternalFilesDir(Environment.DIRECTORY_PICTURES), filename);

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

    // 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 = service.upload(description, requestFile);
    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());
        }
    });
}

1 个答案:

答案 0 :(得分:1)

而不是@Part("file") MultipartBody.Part file

使用@Part MultipartBody.Part file

File file = new File(getRealPathFromURI(data.getData()));

RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), getRealPathFromURI(data.getData()));

MultipartBody.Part multipartBody =MultipartBody.Part.createFormData("file",file.getName(),requestFile);