I tried to upload an image using Retrofit but I am getting this error:
Unable to submit post to API: java.io.FileNotFoundException: /document/image:30231: open failed: ENOENT (No such file or directory)
My interface is like this:
public interface MyService{
@Multipart
@POST("/url")
Call<ResponseBody> addNewEvent( @Part("case_Id") int caseId,@Part MultipartBody.Part(file);
}
On Button click, selectImage()
function is called:
private void selectImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Please select image",1);
}
In the onActivityResult
part, I did the following:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode!=RESULT_CANCELED && resultCode == RESULT_OK && data != null && data.getData() != null) {
FilePathUri = data.getData();
doAddNewEvent();
}
}
From above, doAddNewEvent()
function is called:
public void doAddNewEvent() {
File file = new File(FilePathuri.getPath());
RequestBody requestFile=RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
apiService.addNewEvent(inputCaseId, body).enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
ResponseBody addEventResponse = response.body();
Log.d("as", "response: " + addEventResponse);
finish();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("as", "Unable to submit post to API");
}
});
}
There is a problem to get file path
Try with this :
and make multipart using string path