I cannot able to upload multiple images to server - java

#Multipart
#POST("api/shop/kyc")
Call<String> submit_kycc(#PartMap HashMap<String, RequestBody> map, #Part MultipartBody.Part pan,
#Part MultipartBody.Part bnk_stmt, #Part MultipartBody.Part adar,
#Part MultipartBody.Part fssai_cert, #Part MultipartBody.Part gst_cert,
#Part MultipartBody.Part[] multi_file);
public void submit_kycc1() {
enter_pan_no_str = enter_pan_no.getText().toString().trim();
fssai_num_str = fssai_num.getText().toString().trim();
gst_num_str = gst_num.getText().toString().trim();
adhar_num_str = adhar_num.getText().toString().trim();
if (enter_pan_no_str == null)
validateAadharNumber(enter_pan_no_str);
if (govtIdPath == null) {
Toast.makeText(context, "add pan adar id", Toast.LENGTH_SHORT).show();
} else {
if (isInternet) {
HashMap<String, RequestBody> map = new HashMap<>();
map.put("pan_no", RequestBody.create(MediaType.parse("text/plain"), enter_pan_no_str));
map.put("aadhar_no", RequestBody.create(MediaType.parse("text/plain"), adhar_num_str));
map.put("fssai_no", RequestBody.create(MediaType.parse("text/plain"), fssai_num_str));
map.put("gst_no", RequestBody.create(MediaType.parse("text/plain"), gst_num_str));
File file = new File(govtIdPath);
//RequestBody reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part pan = MultipartBody.Part.createFormData("pan_card", govtIdPath, reqFile);
MultipartBody.Part bnk_stmt = MultipartBody.Part.createFormData("bank_statement", govtIdPath, reqFile);
MultipartBody.Part adar = MultipartBody.Part.createFormData("aadhar_card", govtIdPath, reqFile);
MultipartBody.Part fssai_cert = MultipartBody.Part.createFormData("fssai_certificate", govtIdPath, reqFile);
MultipartBody.Part gst_cert = MultipartBody.Part.createFormData("gst_certificate", govtIdPath, reqFile);
MultipartBody.Part multi_file = MultipartBody.Part.createFormData("menufile[]",govtIdPath,reqFile);
customDialog.show();
Call<String> call = apiInterface.submit_kycc(map,
pan, bnk_stmt, adar, fssai_cert, gst_cert, multi_file);
call.enqueue(new GlobalCallback<String>(enter_pan_no) {
#Override
public void onResponse(Call<String> call, Response<String> response) {
customDialog.dismiss();
String res = response.body().toString();
if (res.contains("1")) {
Toast.makeText(getApplicationContext(), "Successfully Uploaded", Toast.LENGTH_LONG).show();
onBackPressed();
} else if (res.contains("0")) {
Toast.makeText(getApplicationContext(), "failed to upload", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(#NonNull Call<String> call, #NonNull Throwable t) {
customDialog.dismiss();
Utils.displayMessage(KycActivity.this, getString(R.string.something_went_wrong));
}
});
}
}
}

Related

How to send JsonObject Post request with image using Retrofit (Java)

I want to send a post request which contains jsonObject and an image and various other fields and I used MultiPart for image and have successfully uploaded the image but the jsonObject is uploaded in string format
Here is my Api Interface
#Multipart
#POST("operator/upload")
Call<JsonObject>upload(#Header ("Authorization") String t,
#Part MultipartBody.Part img,
#Part("fullName") RequestBody name,
#Part("fatherName") RequestBody fathername,
#Part("aadharNumber") RequestBody aadharnumber,
#Part("dob") RequestBody dob,
#Part("registeredAddress") RequestBody address,
#Part("gender") RequestBody gender,
#Part("plantId") RequestBody plant,
#Part MultipartBody.Part data,
#Part("authorized") Boolean auth,
#Part("verified") Boolean ver) ;
Here is the Retrofit service function
public void userUpload(String p, MultipartBody.Part image, RequestBody name, RequestBody fathername, RequestBody aadharnumber, RequestBody dob, RequestBody address, RequestBody gender, RequestBody plant, MultipartBody.Part cap, Boolean aut, Boolean ver, Response_listner response_listner) {
Call<JsonObject> call = api_interface.upload(p, image, name, fathername, aadharnumber, dob, address, gender, plant,cap,aut,ver);
serveCall(call, response_listner);
}
The ServeCall Method is here
private void serveCall(Call<JsonObject> call, Response_listner responce_listner) {
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
try {
responce_listner.onResponseSuccess(response);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
try {
responce_listner.onResponseFailure(t);
Log.d("Network", t.getMessage());
Log.d("Network Cause", t.getCause().getMessage());
Log.d("NetworkStack", t.getStackTrace().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
And My Main Code where I Made an Api Call
HashMap<String, String> num2 = new HashMap<>();
num2.put("client_id",String.valueOf(CLIENT_ID));
num2.put("full_name",String.valueOf(FULL_NAME));
num2.put("aadhaar_number",String.valueOf(AADHAR_NUMBER));
num2.put("dob",String.valueOf(DOB));
num2.put("gender",String.valueOf(GENDER));
num2.put("face_status",String.valueOf(FACE_STATUS));
num2.put("face_score",String.valueOf(FACE_SCORE));
num2.put("zip",String.valueOf(ZIP));
num2.put("profile_image",String.valueOf(PROFILE_IMAGE));
num2.put("has_image",String.valueOf(HAS_IMAGE));
num2.put("mobile_hash",String.valueOf(MOBILE_HASH));
num2.put("raw_xml",String.valueOf(RAW_XML));
num2.put("zip_data",String.valueOf(ZIP_DATA));
num2.put("care_of",String.valueOf(CARE_OF));
num2.put("share_code",String.valueOf(SHARE_CODE));
num2.put("mobile_verified",String.valueOf(MOBILE_VERIFIED));
num2.put("reference_id",String.valueOf(REFERENCE_ID));
MultipartBody.Part delta = MultipartBody.Part.createFormData("aadharDetails", num2.toString());
RetrofitClient.getInstance_new().userUpload(TokenData, image, name, fathername, aadharnumber, dobb, addresss, genderr, plant,delta, auth, ver, new Response_listner() {
#Override
public void onResponseSuccess(Response baseResponse) throws IOException, JSONException {
if (baseResponse.isSuccessful()) {
Log.e("Response",baseResponse.body().toString());
JSONObject jsonObject = new JSONObject(baseResponse.body().toString());
prog_close();
Intent intent = new Intent(RegisterOP.this, Done.class);
startActivity(intent);
finish();
}
// }
} else {
Toast.makeText(RegisterOP.this, baseResponse.message(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onResponseFailure(Throwable throwable) {
Toast.makeText(RegisterOP.this, throwable.getMessage(), Toast.LENGTH_SHORT).show();
}
});
So the data that I'm sending all is good except delta which is request body somehow it sends string rather than HashMap
Your Help Is Greatly Appreciated !!

How to pass Image files in #PartMap in retrofit Adnroid

My requirement is to pass the request in the below format,
I don't have any idea on how to send request in the below format using a #PartMap,
{
"image", img1.jpg,
"image", img2.jpg,
"service_request", "asd123123asfsf"
}
The type for above format,
{
"<String>", <Image file>,
"<String>", <Image file>,
"<String>", "<String>"
}
My current method
private void uploadMultipleFiles() {
SharedPreferences preferences = getApplicationContext().getSharedPreferences("MY_APP", Context.MODE_PRIVATE);
String retrivedToken = "Token " + preferences.getString("TOKEN", null);
String attachment_one = preferences.getString("Attachement_one", null);
String attachement_two = preferences.getString("Attachement_two", null);
File file_one = new File(attachment_one);
File file_two = new File(attachement_two);
RequestBody requestBody1 = RequestBody.create(MediaType.parse("*/*"), file_one);
RequestBody requestBody2 = RequestBody.create(MediaType.parse("*/*"), file_two);
MultipartBody.Part fileToUpload1 = MultipartBody.Part.createFormData("file1", file_one.getName(), requestBody1);
MultipartBody.Part fileToUpload2 = MultipartBody.Part.createFormData("file2", file_two.getName(), requestBody2);
Call<ResponseBody> call = ServiceBuilder.getInstance().getApi().uploadImages(retrivedToken, "multipart/form-data", fileToUpload1, fileToUpload2, filename);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (!response.isSuccessful()) {
System.out.println("Response Code: " + response.code());
return;
} else {
System.out.println("Response Code: " + response.code());
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
System.out.println("Message: " + t.getMessage());
}
});
}
Service method
#Multipart
#POST("http://192.168.1.100:8000/yrtp/service/request/upload")
Call <ResponseBody> uploadImages(#Header ("Authorization") String token, #Header("Content-Type") String type, #Part MultipartBody.Part file1, #Part MultipartBody.Part file2, #Part("service_request") RequestBody description);
I'm new in using the #PartMap in retrofit and android. Kindly help me with a solution. Million thanks in advance!

Facing Issue while uploading images using android Retrofit 2

i am having some issues regarding upload image using retrofit 2 . i have an api to upload three kind of images like(Profile images , Banner images , Other images). i need to pass three parameters (user_id , type(profile / banner / other) , media(file) )... i am not understanding how to do it ...
here is my interface...
#Multipart
#POST("media/upload_media")
Call<ServerRespose> upload(
#Part MultipartBody.Part file ,
#Query("user_id") int user_id ,
#Query("type") String type
);
and here is my coe where i am trying to do it...
private void uploadFile(String path, Uri fileUri, final int type) {
// create upload service client
uid = DatabaseUtil.getInstance().getUser().getData().getID();
String username = SharedPreferenceUtil.getStringValue(this, Constants.USERNAME);
String password = SharedPreferenceUtil.getStringValue(this, Constants.PASSWORD);
if (!username.isEmpty() && !password.isEmpty()) {
Api service =
RetrofitUtil.createProviderAPIV2(username, password);
//
try {
// use the FileUtils to get the actual file by uri
showProgressDialog("Uploading");
File file = new File(path);
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("file", file.getName(), requestFile);
// finally, execute the request
Call<ServerRespose> call = service.upload(body , uid , "profile_image");
call.enqueue(new Callback<ServerRespose>() {
#Override
public void onResponse(Call<ServerRespose> call,
Response<ServerRespose> response) {
hideProgressDialog();
Log.v("Upload", "success");
ServerRespose item = response.body();
try {
if (item != null) {
// item.setSuccess(true);
if (type == SELECT_PROFILE_PIC) {
profileImageRecyclerViewAdapter.addNewItem(item);
profileImageRecyclerViewAdapter.notifyDataSetChanged();
} else {
bannerImageRecyclerViewAdapter.addNewItem(item);
bannerImageRecyclerViewAdapter.notifyDataSetChanged();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ServerRespose> call, Throwable t) {
AppUtils.showDialog(Profile_Activity.this, "There is some Error", null);
Log.e("Upload error:", t.getMessage());
}
});
} catch (Exception e) {
e.printStackTrace();
}
} else {
showDialogSignedUp("Session Expired Please Login Again...", null);
}
}
Note: My code is not working just pick image and showing uploading and it is also not returning any kind of response ... Any one please help with the correct code i need to do this work on a very short notice.
check the parameters here...
function save_image($request)
{
if(!empty($request['user_id'])){
$user_identity = $request['user_id'];
$submitted_file = $_FILES['media'];
$uploaded_image = wp_handle_upload( $submitted_file, array( 'test_form' => false ) );
$type = $request[ 'type' ];
//return $submitted_file;
if ( !empty( $submitted_file )) {
$file_name = basename( $submitted_file[ 'name' ] );
$file_type = wp_check_filetype( $uploaded_image[ 'file' ] );
// Prepare an array of post data for the attachment.
$attachment_details = array(
'guid' => $uploaded_image[ 'url' ],
'post_mime_type' => $file_type[ 'type' ],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $file_name ) ),
'post_content' => '',
'post_status' => 'inherit'
);
Try this way..
#Multipart
#POST(NetworkConstants.WS_REGISTER)
Call<UserResponseVo> registerUser(#Part MultipartBody.Part file, #PartMap Map<String, RequestBody> map);
after that..
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), mFile);
RequestBody userName = RequestBody.create(MediaType.parse("text"), mEtUserName.getText().toString());
RequestBody userEmail = RequestBody.create(MediaType.parse("text"), mEtEmail.getText().toString().trim());
RequestBody userPassword = RequestBody.create(MediaType.parse("text"), mEtPassword.getText().toString().trim());
Map<String, RequestBody> map = new HashMap<>();
map.put(NetworkConstants.KEY_FIRST_NAME, userName);
map.put(NetworkConstants.KEY_EMAIL, userEmail);
map.put(NetworkConstants.KEY_PASSWORD, userPassword);
retrofit.create(ApiInterface.class).registerUser(fileToUpload, map);
Try this
1)Declare method in interface class
#Multipart
#POST("media/upload_media")
Call<AddImageResponseClass> upload(#Part("user_id") RequestBody user_id, #Part("media\"; filename=\"myfile.jpg\" ") RequestBody profile_pic,#Part("type") RequestBody type);
Then in java class
String BASE_URL=base_url;
final OkHttpClient okHttpClient = new OkHttpClient.Builder().writeTimeout(2, TimeUnit.MINUTES).retryOnConnectionFailure(true)
.readTimeout(2, TimeUnit.MINUTES)
.connectTimeout(2, TimeUnit.MINUTES)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL).client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
Api service =
RetrofitUtil.createProviderAPIV2(username, password);
File file = new File(path);
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file );
String user_id= user_id_here;
String type= type_here;
RequestBody reqUserId= RequestBody.create(MediaType.parse("text/plain"), user_id);
RequestBody reqType= RequestBody.create(MediaType.parse("text/plain"), type);
Call<ServerRespose> userCall = service.upload(reqUserId, reqFile,reqType);
userCall.enqueue(new Callback<ServerRespose>() {
#Override
public void onResponse(Call<ServerRespose> call, Response<ServerRespose> response) {
if (response.body() == null) {
//handle here
return;
}
}
#Override
public void onFailure(Call<ServerRespose> call, Throwable t) {
System.out.println("response failure" + t.getMessage());
t.printStackTrace();
}
});
And import these
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.google.code.gson:gson:2.8.2'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'

Failed multipart upload using retrofit 2

I'm new at retrofit and I want to upload using retrofit 2. Every uploading the file the response is
Fail Upload
from the php but if I'm using Postman it always success.
Below is my code.
Main Activity
File zip = new File(Environment.getExternalStorageDirectory() + "/test.zip");
RequestBody reqBody = RequestBody.create(MediaType.parse("multipart/form-file"), zip);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", zip.getName(), reqBody);
ApiServices api = RetroClient.getApiServices();
Call<ResponseApiModel> upload = api.fileUpload(filePart);
upload.enqueue(new Callback<ResponseApiModel>() {
#Override
public void onResponse(Call<ResponseApiModel> call, Response<ResponseApiModel> response) {
if (response.body().getCode().equals("1")) {
Toast.makeText(MainActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseApiModel> call, Throwable t) {
Log.d("RETRO", "ON FAILURE : " + t.getMessage());
}
});
Api Services
#Multipart
#POST("getzip.php")
Call<ResponseApiModel> fileUpload (#Part MultipartBody.Part File);
PHP Code
$part = "./upload/";
$filename = rand(9,9999).".zip";
$res = array();
$code = "";
$message = "";
if($_SERVER['REQUEST_METHOD'] == "POST")
{
if(isset($_FILES['file'])){
$destinationfile = $part.$filename;
$data = $_FILES['file'];
if(move_uploaded_file($data['tmp_name'], $destinationfile)) {
$code = 1;
$message = "Success Upload";
}else {
$code = 0;
$message = "Fail Upload";
}
}else{
$code = 0;
$message = "request error";
}
}else
{
$code = 0;
$message = "Request Not Vaild";
}
$res['code'] = $code;
$res['message'] = $message;
echo json_encode($res);
I don't know PHP but I know Retrofit. Here is how I do it and works perfectly, this uploads the whole folder, you may change accordingly to handle your files.
You need to use Multipart Format.
Here is a code sample below:
#Multipart
#POST("sync/contact/image")
Call<Response> ImageUpload(#Part MultipartBody.Part file);
#Multipart
#POST("sync/image")
Call<ResponseBody> MultiImageUpload(#PartMap() Map<String, RequestBody> mapFileAndName);
public static HashMap<String, RequestBody> GetAllImage(Context context) {
File files = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "/.ELMEX");
File[] filesArray = files.listFiles();
List<File> listOfNames = Arrays.asList(filesArray);
HashMap<String, RequestBody> map = new HashMap<>(listOfNames.size());
RequestBody file = null;
for (int i = 0, size = listOfNames.size(); i < size; i++) {
file = RequestBody.create(MediaType.parse("multipart/form-data"), listOfNames.get(i));
map.put("file\"; filename=\"" + listOfNames.get(i).getName() + ".jpg", file);
file = null;
}
return map;
}
HashMap<String, RequestBody> map = UtilImage.GetAllImage(context);
Call<ResponseBody> call = Retro.getRetroWS().MultiImageUpload(map);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d(TAG, "onResponse: ");
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d(TAG, "onFailure: ");
}
});
You can check all the suggestions given in this answer. Check out all the answers and comments, not just the accepted answer, because there are some really good ideas on what could be wrong, as well as good ideas on how to debug the problem.

Upload file using retrofit 2 even if null

I have an application where the user can add comment, location and optional image to the SqlLiteDatabse. On a button press a sync images will sync all images in the db (by path of course). My problem is when the file is null, it will return onFaiulre com.google.gson.stream.MalformedJsonException.
private void syncImage(final int id, String imagePath, String message, String location) {
final SQLiteDatabase db = dbHelper.getWritableDatabase();
File file = null;
if(imagePath!= null && !imagePath.equals(""))
file = new File(imagePath);
alertDialog.setTitle("Uploading.. ");
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
MultipartBody.Part uploaded_file = null;
if(file !=null) {
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
uploaded_file =
MultipartBody.Part.createFormData("uploaded_file", file.getName(), requestFile);
}
RequestBody image_message =
RequestBody.create(
MediaType.parse("multipart/form-data"), message);
RequestBody user_location =
RequestBody.create(
MediaType.parse("multipart/form-data"), location);
Call<String> call = new ApiService().getApiService().upload(image_message, user_location, uploaded_file);
call.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, retrofit2.Response<String> response) {
if (response.isSuccessful()) {
progressDialog.setProgress(progressDialog.getProgress() + singleProgress);
ContentValues contentValues = new ContentValues();
contentValues.put(ImageContract.IMAGE_SYNKED, "true");
db.update(ImageContract.TABLE_NAME, contentValues, ImageContract.IMAGE_ID + "=" + id, null);
Log.d("retrofit", "image uploaded");
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.d("db", t.toString());
}
});
}
I'm wondering how can I upload an optional file ?
Log:
db: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $
String mem_email_str = edit_email.getText().toString().trim();
RequestBody mem_email = RequestBody.create(MultipartBody.FORM,mem_email_str);
MultipartBody.Part body = null;
Call<String> call;
if(profile_file != null){
RequestBody file = RequestBody.create(MediaType.parse("multipart/form-data"),profile_file);
body = MultipartBody.Part.createFormData("file",profile_file.getName(),file);
call = httpService.mobileInsertMember(mem_email,body);
}else{
RequestBody file = RequestBody.create(MultipartBody.FORM,"");
body = MultipartBody.Part.createFormData("file","",file);
call = httpService.mobileInsertMember(mem_email,body);
}

Categories

Resources