簡體   English   中英

Android Retrofit 2文件上傳

[英]Android Retrofit 2 file upload

我正在使用Retrofit 2,並且想調用一個Web服務以將圖像上傳到服務器。 服務器端,我使用的是Phalcon PHP ,我檢查是否有要上傳的文件。 但是我從來沒有要上傳的文件。 我可以獲取description參數,但不能獲取file參數。

你能告訴我我的Android代碼是否正常嗎? 我不知道怎么了

應用服務

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM