嗨,我无法使用改造 2.0.0-beta2 上传图像。它给了我“图像丢失”错误。尽管我检查了该文件是否存在于系统中,并且如果我在图像视图中显示它也可以正确显示。
需要上传的 URL:http: //mywebsite.com/signature/upload/
所以我的 BASE_URL 是 = http://mywebsite.com/
我的.gradle文件有这个:
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
compile 'com.squareup.okhttp:logging-interceptor:2.6.0'
SeriveGenerator.java类是
public class ServiceGenerator {
public static final String API_BASE_URL = Urls.URL_BASE;
private static OkHttpClient httpClient = new OkHttpClient();
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();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.interceptors().add(interceptor);
return retrofit.create(serviceClass);
}
}
UploadService.java类是
public interface UploadService {
@Multipart
@POST("/signature/upload/")
// Tried to change this to "/signature/upload" as well (no slash in end)
// then gives Method not allowed error"
Call<String> upload(
@Part("image") RequestBody file,
@Part("image_name") String name);
}
最后在我的 android 活动中
// photoFile is the file, checked that it exist in system and
// path is also correct
public void uploadFileToServer() {
UploadService service =
ServiceGenerator.createService(UploadService.class);
String name = "xyz.jpg";
RequestBody requestBody =
RequestBody.create(MediaType.parse("multipart/form-data"), photoFile);
Call<String> call = service.upload(requestBody, name);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Response<String> response, Retrofit retrofit) {
Log.v("Upload", "success");
}
@Override
public void onFailure(Throwable t) {
Log.e("Upload", t.getMessage());
}
});
}
所以我从活动中获得成功日志“成功”,但服务器文件不存在,使用邮递员,我尝试手动上传表单数据中的图像,正确上传。