I have looked through many stackoverflow answers but could not upload image. It used to give me Internal Server Error. Now I found a solution but it sends a null image to the server. Could you please show me where I am doing wrong.
Here is my Request CODE:
#Multipart
#POST("lostandfound")
Call<ResponseBody> uploadLostAndFound(#PartMap Map<String, RequestBody> map);
And my CALL:
Map<String, RequestBody> map = new HashMap<>();
map.put("usermail", toRequestBody("mohammad_sed"));
map.put("content", toRequestBody(content));
map.put("islost", toRequestBody(String.valueOf(isLost)));
map.put("wasfound", toRequestBody(foundPlace));
map.put("tofind", toRequestBody(toFindPlace));
File file = new File(destination);
RequestBody reqFile = RequestBody.create(MediaType.parse("image"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);
map.put("img", body);
ForumService client = Utils.getBuilder().create(ForumService.class);
Call<ResponseBody> call = client.uploadLostAndFound(map);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
mProgressDialog.dismiss();
// Toast.makeText(getApplicationContext(), "Request created", Toast.LENGTH_SHORT).show();
} else {
mProgressDialog.dismiss();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
mProgressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Failed to upload!", Toast.LENGTH_SHORT).show();
}
});
// This method converts String to RequestBody
public static RequestBody toRequestBody(String value) {
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), value);
return body;
}
I tried:
#Multipart
#POST("lostandfound")
Call<ResponseBody> uploadLostAndFound(#Part MultipartBody.Part photo,
#PartMap Map<String, RequestBody> map);
But this way I get Internal server error.
Thanks in advance.
I found the solution. I tried from postman and it was working fine.
The solution is that I had to use:
#Multipart
#POST("lostandfound")
Call<ResponseBody> uploadLostAndFound(#Part MultipartBody.Part photo,
#PartMap Map<String, RequestBody> map);
and:
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("img", file.getName(), reqFile);
The change is I had to use "img" instead of "upload". That is a stupid mistake :D
Related
Hi in the below code below code is my php code.I want to send file from my client .client to sending file as well as filename.I want to sent all the parameters from android app and send to the server.below php code from server based on server I am sending from the client but it is not working
Can any one help me where I did the mistake
example.php:
$data = array(
'_session'=>$session,
'file' => $file,
'_operation' => 'saveRecord',
'module' => $module,
'sourceModule' => 'Potentials',
'sourceRecord' => '13x37913',
'values' => json_encode(array('notes_title'=>'test','filename' => $_FILES['file']['name'],'assigned_user_id'=>1,"filelocationtype"=>"I", "filestatus"=>1))
);
below is my api with the following parameters as below
Api.java:
#POST("api.php")
#Multipart
Call<SaveContactModule> SaveDocuments(#Part MultipartBody.Part operation,
#Part MultipartBody.Part session,
#Part MultipartBody.Part module,
#Part MultipartBody.Part sourceRecord,
#Part MultipartBody.Part values,
#Part MultipartBody.Part sourceModule,
#Part MultipartBody.Part file);
below activity I am sending to the server but somewhere I did the misatke.
MainActivity.java:
private void saveclosedwon() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Loading...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
progressDialog.show();
sessionId = getActivity().getIntent().getStringExtra("sessionId");
String operation = "saveRecord";
sourceRecord = "13x53090";
String module = "Documents";
String sourceModule = "Potentials";
// RequestBody requestFile = RequestBody.create(MediaType.parse(getContext().getContentResolver().getType(filePath)), mPhotoFile);
JSONObject postdata = new JSONObject();
MultipartBody.Part body = MultipartBody.Part.createFormData("file", filename, requestFile);
try {
postdata.put("notes_title", notes_title);
postdata.put("filename", filename);
postdata.put("assigned_user_id", ids);
postdata.put("filelocationtype", "I");
postdata.put("filestatus", "1");
} catch (JSONException e) {
e.printStackTrace();
}
//String values= postdata.getString(firstname,lastname,jobtile,contacttype,speclization,mobiles,email);
final GetNoticeDataService service = RetrofitInstance.getRetrofitInstance().create(GetNoticeDataService.class);
MultipartBody.Part session = MultipartBody.Part.createFormData("_session",sessionId);
MultipartBody.Part operation_won = MultipartBody.Part.createFormData("operation",operation);
MultipartBody.Part module_won = MultipartBody.Part.createFormData("module",module);
MultipartBody.Part sourceRecord_won = MultipartBody.Part.createFormData("sourceRecord",sourceRecord);
MultipartBody.Part sourceModule_won = MultipartBody.Part.createFormData("sourceModule",sourceModule);
MultipartBody.Part sourceModule_postdata = MultipartBody.Part.createFormData("values",postdata.toString());
MultipartBody.Part file = MultipartBody.Part.createFormData("file", "file");
/** Call the method with parameter in the interface to get the notice data*/
Call<SaveContactModule> call = service.SaveDocuments(operation_won, session, module_won, sourceRecord_won, sourceModule_postdata, sourceModule_won,body);
/**Log the URL called*/
Log.i("URL Called", call.request().url() + "");
call.enqueue(new Callback<SaveContactModule>() {
#Override
public void onResponse(Call<SaveContactModule> call, Response<SaveContactModule> response) {
Log.e("response", new Gson().toJson(response.body()));
if (response.isSuccessful()) {
Log.e("response", new Gson().toJson(response.body()));
SaveContactModule saveContactModule = response.body();
String success = saveContactModule.getSuccess();
if (success.equals("true")) {
progressDialog.dismiss();
Toast.makeText(getContext(), "Successfully saved", Toast.LENGTH_LONG).show();
fragment = new SalesStageFragment();
loadFragment(fragment);
} else {
progressDialog.dismiss();
Toast.makeText(getContext(), "Invalid details", Toast.LENGTH_LONG).show();
}
}
progressDialog.dismiss();
}
#Override
public void onFailure(Call<SaveContactModule> call, Throwable t) {
Log.d("error", t.getMessage());
progressDialog.dismiss();
}
});
}
}, 0);
return;
}
As you implemented both multipart and formurlencoded. As per your error it is said that either you should use #Multpart or #FormUrlEncoded but not both at once in the api call. i.e,
#FormUrlEncoded
Call<SaveContactModule> SaveDocuments(#Field("_operation") String operation,
#Field("_session") String session,
#Field("module") String module,
#Field("sourceRecord") String sourceRecord,
#Field("values") JSONObject values,
#Field("sourceModule") String sourceModule,
#Part RequestBody file,
#Part("file") Uri image);
or,
#Multipart
Call<SaveContactModule> SaveDocuments(#Part MultipartBody.Part String operation,
#Part MultipartBody.Part session,
#Part MultipartBody.Part module,
#Part MultipartBody.Part sourceRecord,
#Part MultipartBody.Part values,
#Part MultipartBody.Part sourceModule,
#Part MultipartBody.Part file,
#Part MultipartBody.Part image);
but not both annotations at once.
I am facing problem when sending file through retrofit2. But the web api working fine on Postman hit. Error Stated in responsebody:
Response{protocol=http/1.1, code=404, message=Not Found, url=MYURL}
Retrofit2 endpoint:
#Multipart
#POST("FileStorage/UploadDataFile")
Call<ResponseBody> uploadFile(#Part MultipartBody.Part file,#Part("file") RequestBody name);
Updated code:
// Uploading File
private void uploadFile() {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +
File.separator + "dbBackup"+
File.separator +"gps_db_4522_190122114644.sqlite");
//File file = new File(mediaPath);
Retrofit retrofit = RetrofitSingleton.getInstance(getActivity().getBaseContext());
final CommonApiInterface commonApiInterface = retrofit.create(CommonApiInterface.class);
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());
commonApiInterface.uploadFile(fileToUpload,filename).enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.isSuccessful()) {
Toast.makeText(getActivity(), "Saved Successfully...", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getActivity(), "Save Fail: " + t, Toast.LENGTH_SHORT).show();
}
});
}
Finally i found my problem. The endpoint was incorrect
#Multipart
#POST("FileStorage/UploadDataFile")
Call<ResponseBody> uploadFile(#Part MultipartBody.Part file,#Part("file") RequestBody name);
correct endpoint is #POST("FileProcessing/UploadDataFile")
I want to upload zip file on myserver. I am using Retrofit2. I have used the following code.
private void uploadFile() {
// create upload service client
FileUploadService service =
ServiceGenerator.createService(FileUploadService.class);
File file = uploadFile;
RequestBody requestFile =
RequestBody.create(
MediaType.parse("application/x-www-form-‌urlencoded"),
file
);
MultipartBody.Part body =
MultipartBody.Part.createFormData("fileUpload", file.getName(), requestFile);
String descriptionString = "hello, this is description speaking";
RequestBody description =
RequestBody.create(
okhttp3.MultipartBody.FORM, descriptionString);
Call<JSONObject> call = service.upload(description, body);
call.enqueue(new Callback<JSONObject>() {
#Override
public void onResponse(Call<JSONObject> call,
Response<JSONObject> response) {
System.out.println("UploadFragment.onResponse " + response);
Log.v("Upload", "success");
}
#Override
public void onFailure(Call<JSONObject> call, Throwable t) {
Log.d("Upload error:", t.getCause().toString());
}
});
}
My upload service is like.
public interface FileUploadService {
#Multipart
#POST("myurl")
Call<JSONObject> upload(
#Part("description") RequestBody description,
#Part MultipartBody.Part file
);
}
Problem When I upload file I get response {protocol=http/1.1, code=200, message=OK, url=http://myUrl.
It is not the response returned by my server. How can get my server response?
Its retrofit response. You will get your response in body.
response.body().toString();
Use this
System.out.println("UploadFragment.onResponse " + response.body().toString());
I hope this will help you.
Hello i am working on upload image file using retrofit.
Can any one have idea how to pass in
You need pass mulitypart object in retrofit:
MultipartBody.Part carImage = null;
if (!TextUtils.isEmpty(imagePath)) {
File file = FileUtils.getFile(getContext(), imagePath);
// create RequestBody instance from file
final RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
carImage = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
}
public static MultipartBody.Part UploadImage(String filePath,String param) {
MultipartBody.Part body = null;
try {
body = MultipartBody.Part.createFormData("", "", null);
} catch (Exception e) {
e.printStackTrace();
}
//profileUpdateRequest.setWebsite(lblWebsite.getText().toString().trim());
if ((!filePath.equals(""))) {
File file = new File(filePath);
RequestBody photo = RequestBody.create(MediaType.parse("image/*"), file);
body = MultipartBody.Part.createFormData(param, file.getName(), photo);
}
return body;
}
Step::1Pass the file Path and it will return you MultiPart body
#Multipart
#POST(Endpoint.POST_URL)
Call<DecisionStepThirdResponse> uploadUserProfile(#Part("api_id") RequestBody api_id,
#Part("api_secret") RequestBody api_secret,
#Part("api_request") RequestBody api_request,
#Part("data") RequestBody data,
#Part MultipartBody.Part profile_image);
========================
Step 2: Pass the Request like this
public void uploadUserProfile(UpdateImageRequest request, MultipartBody.Part file, Callback<UpdateImageResponse> callback) {
String api_request = "uploadUserProfile";
String data = new Gson().toJson(request);
IRoidAppHelper.Log("application_form_permission", data);
json().uploadUserProfile(
RequestBody.create(MediaType.parse("text/plain"), api_id),
RequestBody.create(MediaType.parse("text/plain"), api_secret),
RequestBody.create(MediaType.parse("text/plain"), api_request),
RequestBody.create(MediaType.parse("text/plain"), data)
, file).enqueue(callback);
}
Step 3 : And Pass the Parameter in your Serviceclass
Please go through the following link.
Have time to refer this link :)
https://medium.com/#adinugroho/upload-image-from-android-app-using-retrofit-2-ae6f922b184c#.iinz6neii
Step 1: First initialize service class
public interface ImageUploadService {
#Multipart
#POST("upload")
Call<ResponseBody> upload(
#Part("description") RequestBody description,
#Part MultipartBody.Part file
);
}
Step 2: in next step use this where you want to upload image or file
private void uploadFile(Uri fileUri) {
// create upload service client
FileUploadService service =
ServiceGenerator.createService(ImageUploadService.class);
// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
// use the FileUtils to get the actual file by uri
File file = FileUtils.getFile(this, fileUri);
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
file
);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("picture", file.getName(), requestFile);
// add another part within the multipart request
String descriptionString = "hello, this is description speaking";
RequestBody description =
RequestBody.create(
okhttp3.MultipartBody.FORM, descriptionString);
// finally, execute the request
Call<ResponseBody> call = service.upload(description, body);
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());
}
});
}
Step 3: you can use like this
uploadFile(Uri.fromFile(new File("/sdcard/cats.jpg")));
In your activity.
Last step: you need to add
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
In manifest in additon with
<uses-permission android:name="android.permission.INTERNET"/>
Refer this.
You can upload any type of file.
/* Create interface like below. */
public interface uploadWishImage {
#Multipart
#POST("upload/image")
Call<JsonObject> postImage(#Part MultipartBody.Part image, #Part("name") RequestBody name);
}
/* image upload code */
File file = new File("here your file path");
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), reqFile);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "file");
uploadWishImage postService = RetrofitApi.makeNetworkRequestWithHeaders(AddWish.this).create(uploadWishImage.class);
Call<JsonObject> call = postService.postImage(body, name);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
// somethings to do with reponse
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
// Log error here since request failed
}
});
Here is code that I am using to upload image to server. But its not sending right value like user_id so that it shows me wrong result. When I hit api on chrome its working fine it gives proper result. I was using code with uploading Image is :
#Multipart
#POST("/queli_technologies/index.php/Webservice")
Call<EditProfileResponse> editProfile(#Part("u_id") String firstname,
#Part("f_name") String lastname,
#Part("l_name") String email,
#Part("c_no") String password,
#Part MultipartBody.Part file,
#Part("edit_profile") String register);
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"),file);
MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);
service = RetroClient.getApiService();
Call<EditProfileResponse> responseCall = service.editProfile("44","Demo","android","0987654321",body,"edit_profile");
responseCall.enqueue(new Callback<EditProfileResponse>() {
#Override
public void onResponse(Call<EditProfileResponse> call, Response<EditProfileResponse> response) {
if (response.isSuccessful()){
EditProfileResponse res = response.body();
Log.e("Response " , res.getStatus() + " message : " + res.getMessage());
dialog.dismiss();
}
}
#Override
public void onFailure(Call<EditProfileResponse> call, Throwable t) {
}
});
When i donot get proper result i use this:
#Multipart
#POST("/queli_technologies/index.php/Webservice")
Call<EditProfileResponse> editProfile(#Part("u_id") RequestBody userId,
#Part("f_name") RequestBody frstname,
#Part("l_name") RequestBody lastname,
#Part("c_no") RequestBody contctnum,
#Part MultipartBody.Part file,
#Part("edit_profile") RequestBody edit);
File file = new File(BaseActivity.basicImagePath);
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);
service = RetroClient.getApiService();
String text = "31";
RequestBody useridbody =RequestBody.create(MediaType.parse("text/plain"), text);
RequestBody fnbody =RequestBody.create(MediaType.parse("text/plain"), "Demo");
RequestBody lnbody =RequestBody.create(MediaType.parse("text/plain"), "android");
RequestBody conbody =RequestBody.create(MediaType.parse("text/plain"), "0987654321");
RequestBody isbody =RequestBody.create(MediaType.parse("text/plain"), "edit_profile");
Call<EditProfileResponse> responseCall = service.editProfile(useridbody,fnbody,lnbody,conbody,body,isbody);
responseCall.enqueue(new Callback<EditProfileResponse>() {
#Override
public void onResponse(Call<EditProfileResponse> call, Response<EditProfileResponse> response) {
if (response.isSuccessful()){
EditProfileResponse res = response.body();
Log.e("Response " , res.getStatus() + " message : " + res.getMessage());
dialog.dismiss();
}
}
#Override
public void onFailure(Call<EditProfileResponse> call, Throwable t) {
Log.e("Failure Response " , t +"");
}
});
Still Im not able get right result. Api response in Log gives {"status":"0","message":"User doesnot exist"} when using through retrofit. and from
server it shows {"status":"1","message":"User profile Updated"}
Is this retrofit issue or my coding issue?
Move the file to last.
#POST("/queli_technologies/index.php/Webservice")
Call<EditProfileResponse> editProfile(#Part("u_id") String firstname,
#Part("f_name") String lastname,
#Part("l_name") String email,
#Part("c_no") String password,
#Part("edit_profile") String register,
#Part MultipartBody.Part file);
I think, it should work.