【问题标题】:Android Retrofit 2 file uploadAndroid Retrofit 2 文件上传
【发布时间】:2018-04-26 19:46:46
【问题描述】:

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

你能告诉我我的安卓代码是否正常吗?不知道怎么回事。

应用服务

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

【问题讨论】:

    标签: android file-upload retrofit2


    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 2017-03-28
      • 2016-08-31
      • 2016-09-04
      • 2017-05-14
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      相关资源
      最近更新 更多