Android Retrofit 2文件上传 [英] Android Retrofit 2 file upload

查看:180
本文介绍了Android Retrofit 2文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

你能告诉我,如果我的android代码是好的吗?我不知道什么是错的。
$ b

ApplicationService

  public interface ApplicationService {

...
//我的其他web服务运行良好

@Multipart
@POST / path / to / uploadPictures)
呼叫< ResponseBody>上传(@Part(description)RequestBody描述,
@Part(file)RequestBody文件);

$ b

ServiceGenerator Class

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




$ b

上传文件

  private void uploadFile(String filename){
//创建上传服务客户$ b $ ApplicationService service = ServiceGenerator.createService(ApplicationService.class);

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

//从文件
创建RequestBody实例RequestBody requestFile = RequestBody.create(MediaType.parse(multipart / form-data),file);

//在多部分请求中添加另一部分
字符串descriptionString =你好,这是描述说;
RequestBody description = RequestBody.create(MediaType.parse(multipart / form-data),descriptionString);

//最后,执行请求
调用< 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());
}
});

$ / code $


解决方案

而不是 @Part 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);


I'm using Retrofit 2 and I want to call a web service to upload my images to my server. Server side i'm using Phalcon PHP and I check if I have a file to upload. But I have never a file to upload. I can get the description parameter but not the file parameter.

Could you tell me if my android code is ok ? I don't know what is wrong.

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 Class

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

}

Upload file calling

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

解决方案

instead of @Part MultipartBody.Part file

use@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);

这篇关于Android Retrofit 2文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆