【发布时间】:2016-11-26 17:30:10
【问题描述】:
我想使用 Retrofit2 将我的图库图片上传到服务器。 API 有 1 个参数,其中包含作为表单数据的 flie,另一个参数是带有键的标题。当我将图像上传到服务器时,我从服务器收到 File not found 消息。我正在发送正确的文件名,但我不知道为什么会这样。谁能帮我解决。下面是我的代码。
final ProgressDialog progressDialog;
progressDialog = new ProgressDialog(UserProfileActivity.this);
progressDialog.setMessage("Updating Data");
progressDialog.show();
//Create Upload Server Client
ApiService service = RetroClient.getApiService();
//File creating from selected URL
File file = new File(imgDecodableString);
Log.d("TAG","file="+file.getName());
// create RequestBody instance from file
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("image", file.getName(), requestFile);
Call<com.example.datamodel.Response> resultCall = service.uploadImage(loginHash,body);
resultCall.enqueue(new Callback<com.example.datamodel.Response>() {
@Override
public void onResponse(Call<com.example.datamodel.Response> call, retrofit2.Response<com.example.datamodel.Response> response) {
com.example.datamodel.Response mBean = response.body();
if(null != mBean)
{
Log.d("TAG","RS="+mBean.getMessage());
Log.d("TAG","RS="+mBean.getData().getvImage());
}
progressDialog.dismiss();
}
@Override
public void onFailure(Call<com.example.datamodel.Response> call, Throwable t) {
progressDialog.dismiss();
Log.d("TAG", "fail=" + t.getMessage());
}
});
RetroClient.java
public class RetroClient {
public RetroClient() {
}
private static Retrofit getRetroClient() {
return new Retrofit.Builder()
.baseUrl(AppConstants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static ApiService getApiService() {
return getRetroClient().create(ApiService.class);
}}
ApiService.java
public interface ApiService {
@Multipart
@POST("api/User/uploadUserProfilePhoto")
Call<Response> uploadImage(@Header("vLoginHash") String vLoginHash,@Part MultipartBody.Part file);}
在 logcat 中,我收到来自服务器的 File not found 消息。任何人请帮忙。提前致谢。
【问题讨论】:
-
使用这个可能对stackoverflow.com/a/40608320/5305430有帮助
-
@sushildlh 我已经这样做了,并且还更改了 MediaType.parse("image/*") 但仍然是同样的错误
标签: android image-uploading multipartform-data retrofit2