问题
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());
}
});
}
回答1:
instead of @Part("file") 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);
来源:https://stackoverflow.com/questions/36013552/android-retrofit-2-file-upload