I have a post API which accept photo with one multipart photo and a string title as a body now I want to use retrofit to upload photo which I got error with null response
my interface code is :
public interface UploadPhotoApi {
@Multipart
@POST("files/")
Call<FileUpdloadResponse> upload(
@Part MultipartBody.Part file,
@Part("title") RequestBody title
);}
and my code for uploading file is :
File file = FileUtils.getFileFromUri(getContext(),uri);//make file from uri
RequestBody requestFile =
RequestBody.create(file,MediaType.parse("image/*"));
MultipartBody.Part body =
MultipartBody.Part.createFormData("image", file.getName(), requestFile);
//String title = file.getName();
RequestBody title =
RequestBody.create(
file.getName(),MediaType.parse("text/plain"));
Call<FileUpdloadResponse> call = uploadPhotoApi.upload(body,title);
call.enqueue(new Callback<FileUpdloadResponse>() {
@Override
public void onResponse(Call<FileUpdloadResponse> call, Response<FileUpdloadResponse> response) {
try {
pk = response.body().getPk();
imageView.setImageURI(uri);
makeVisible(getString(R.string.photo_uploaded));
}catch (Exception e){
Log.i("Log12", "exception2 is" + e.toString());
makeVisible(getString(R.string.photo_not_uploaded));
}
}
@Override
public void onFailure(Call<FileUpdloadResponse> call, Throwable t) {
makeVisible(getString(R.string.photo_not_uploaded));
Log.i("Log12", "failure is" + t.toString());
}
});
If I get a correct response from server it should have pk in response model. but pk is null so catch part run and show error uploading to user ...
I tried many things in similar questions but I didn't found any right solution to solve my problem.
and file utils is this code :
So I'm sorry if I asked a repeated question .... for example I read this article but didn't helped: How to upload an image file in Retrofit 2