Facing Issue while uploading images using android Retrofit 2 - java

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'

Related

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!

Why does PDF is not able to upload in PHP API for Android Pie, Q and R using Retrofit 2 in Android/Java? [Not solved]

I tried to upload a PDF file [Not Image] in PHP API from Android, and I'm getting 400 with this exception:
{"head":{"StatusValue":400,"StatusText":"Failed"},"body":{"Error":"Missing required property fileId"}}
I'm getting 200 request code, when I'm doing in Postman:
Now, Android code:
#Multipart
#POST("eligibity/auth/attachment/upload/add")
Call<ResponseBody> uploadFile(#Part MultipartBody.Part file, #Part("fileName") RequestBody name, #Part("body") JSONObject body);
private void uploadPDF(String path) {
String pdfname = String.valueOf(Calendar.getInstance().getTimeInMillis());
File file = new File(path);
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("fileName", file.getName(), requestBody);
RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), pdfname);
try {
JSONObject sJsonAttachment = new JSONObject();
JSONObject body = new JSONObject();
sJsonAttachment.put("appointmentId", AdapterCollections.clsClaimDiscussionList.get(position).appointment_id);
sJsonAttachment.put("createdBy", Integer.parseInt(preferenceManager.getUserId()));
sJsonAttachment.put("customerId", Integer.parseInt(preferenceManager.getCustomerId()));
sJsonAttachment.put("encounterId", AdapterCollections.clsClaimDiscussionList.get(position).encounter_id);
sJsonAttachment.put("expiryDate", Utility.getCurrentDate("MM-DD-YY"));
sJsonAttachment.put("fbType", 4);
sJsonAttachment.put("fileId", 0);
sJsonAttachment.put("fileName", "name");
sJsonAttachment.put("insTpaPatId", 0);
sJsonAttachment.put("isActive", 1);
sJsonAttachment.put("messageId", AdapterCollections.clsClaimDiscussionList.get(position).log_messages.get(position).log_id);
sJsonAttachment.put("patientId", AdapterCollections.clsClaimDiscussionList.get(position).patient_id);
sJsonAttachment.put("recType", "");
sJsonAttachment.put("reportDate", Utility.getCurrentDate("DD-MM-YYYY"));
sJsonAttachment.put("siteId", Integer.parseInt(preferenceManager.getSiteId()));
sJsonAttachment.put("type", 4);
sJsonAttachment.put("uploadDate", Utility.getCurrentDate("MMDDYY"));
// body.put("body", sJsonAttachment);
ApiCall apiCall = RetrofitService.createService(SCMS_BASE_URL, ApiCall.class);
assert apiCall != null;
apiCall.uploadFile(fileToUpload, filename, sJsonAttachment).enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(#NotNull Call<ResponseBody> call, #NotNull Response<ResponseBody> response) {
try {
showLog("STATUS: " + response.code());
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(#NotNull Call<ResponseBody> call, #NotNull Throwable t) {
showLog("FAILED: "+ t.getMessage());
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
I know that I'm doing somewhere small mistakes, but not able to spot that.
If I used part then this error: Missing required property fileId, and if I use query then this error: must be object.
Update
Regarding Path:
provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="/storage/emulated/0" path="."/>
</paths>
Intent to open PDF chooser:
private void fileDialog() {
Intent intent = new Intent().setType("application/pdf").setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(Intent.createChooser(intent, "Select PDF file"), 123);
}
I followed this https://stackoverflow.com/a/62830720/12630878 answer to getPath, but, I'm NOT getting path properly.
Higher version means: 28 to 30
Higher Version URI:
URI: content://com.android.providers.media.documents/document/document%3A31
FROM RECENT, If I'll choose PDF, then cursor is returning null:
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
FROM DOWNLOADS, if I'll choose PDF, then NumberFormatException coming on this line:
URI: content://com.android.providers.downloads.documents/document/msf%3A27
Exception: java.lang.NumberFormatException: For input string: "msf:27"
LINE NO: Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
FileUtils class: https://drive.google.com/file/d/1S5-Sdp_CCSXXsOsZxwuhv0F5_CtH2EQO/view?usp=sharing
Search this method where I'm getting Path:
public static File getFile(Context context, Uri uri) {
if (uri != null) {
String path = getPathForAllVersion(context, uri);
// String path = getFilePathFromURI(context, uri);
showLog("isPATH: " + path);
if (checkNull(path) && isLocal(path)) {
return new File(path);
}
}
return null;
}
You api accept only two parameters but you passed three parameters that's why you getting error.
so API method should be
#Multipart
#POST("eligibity/auth/attachment/upload/add")
Call<ResponseBody> uploadFile(
#Part("body") RequestBody description,
#Part MultipartBody.Part file
);
And update your uploadPDF() like below
private void uploadPDF(String path) {
//json data
JSONObject sJsonAttachment = new JSONObject();
JSONObject body = new JSONObject();
sJsonAttachment.put("appointmentId", AdapterCollections.clsClaimDiscussionList.get(position).appointment_id);
sJsonAttachment.put("createdBy", Integer.parseInt(preferenceManager.getUserId()));
sJsonAttachment.put("customerId", Integer.parseInt(preferenceManager.getCustomerId()));
sJsonAttachment.put("encounterId", AdapterCollections.clsClaimDiscussionList.get(position).encounter_id);
sJsonAttachment.put("expiryDate", Utility.getCurrentDate("MM-DD-YY"));
sJsonAttachment.put("fbType", 4);
sJsonAttachment.put("fileId", 0);
sJsonAttachment.put("fileName", "name");
sJsonAttachment.put("insTpaPatId", 0);
sJsonAttachment.put("isActive", 1);
sJsonAttachment.put("messageId", AdapterCollections.clsClaimDiscussionList.get(position).log_messages.get(position).log_id);
sJsonAttachment.put("patientId", AdapterCollections.clsClaimDiscussionList.get(position).patient_id);
sJsonAttachment.put("recType", "");
sJsonAttachment.put("reportDate", Utility.getCurrentDate("DD-MM-YYYY"));
sJsonAttachment.put("siteId", Integer.parseInt(preferenceManager.getSiteId()));
sJsonAttachment.put("type", 4);
sJsonAttachment.put("uploadDate", Utility.getCurrentDate("MMDDYY"));
// create RequestBody instance from file
File file=new File(path);
RequestBody requestFile =
RequestBody.create(
MediaType.parse(Files.probeContentType(file.toPath()))),
file
);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part fileBody =
MultipartBody.Part.createFormData("fileName", file.getName(), requestFile);
// add another part within the multipart request
RequestBody bodyJsonAttachment =
RequestBody.create(
okhttp3.MultipartBody.FORM, sJsonAttachment.toString());
ApiCall apiCall = RetrofitService.createService(SCMS_BASE_URL, ApiCall.class);
assert apiCall != null;
apiCall.uploadFile(fileBody, bodyJsonAttachment).enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(#NotNull Call<ResponseBody> call, #NotNull Response<ResponseBody> response) {
try {
showLog("STATUS: " + response.code());
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(#NotNull Call<ResponseBody> call, #NotNull Throwable t) {
showLog("FAILED: "+ t.getMessage());
}
});
}
Note : if you getting warning error on mime type, update it
If you are using multipart then pass all the field in Multipart just like this.
Declare method in Api interface just like this. Only one MultipartBody field.
#Multipart
#POST("eligibity/auth/attachment/upload/add")
Call<ResponseBody> uploadFile(#Body MultipartBody body);
Create MultipartBody.Builder add your and your field in it.
MultipartBody.Builder requestBodyBuilde = MultipartBody.Builder().setType(MultipartBody.FORM);
//adding image in multipart
File file = File(selected_file_path);
RequestBody fileBody = ProgressRequestBody(file, this);
requestBodyBuilde.addFormDataPart("fileName", file.name, fileBody);
//add your other field just like this
requestBodyBuilde.addFormDataPart("body", sJsonAttachment );
ApiCall apiCall = RetrofitService.createService(SCMS_BASE_URL, ApiCall.class);
assert apiCall != null;
//Note here we will pass only one parameter that is multipartBody
apiCall.uploadFile(requestBodyBuilde.build()).enqueue(new
Callback<ResponseBody>() {
#Override
public void onResponse(#NotNull Call<ResponseBody> call, #NotNull Response<ResponseBody> response) {
try {
showLog("STATUS: " + response.code());
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(#NotNull Call<ResponseBody> call, #NotNull Throwable t) {
showLog("FAILED: "+ t.getMessage());
}
});
} catch (Exception e) {
e.printStackTrace();
}

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.

Android: how to create post xml-rpc request with custom http header & content type

I want to creat xml-rpc POST request, and pass 2 parameters "application_name" & "key", and change content type to "application/x-www-form-urlencoded" like my code below.
try {
XMLRPCClient oneTimeKeyClient = new XMLRPCClient(new URL(URL_REQUEST_SAMPLE), XMLRPCClient.FLAGS_DEFAULT_TYPE_STRING);
oneTimeKeyClient.setCustomHttpHeader("X-HTTP-METHOD-OVERRIDE", "POST");
// oneTimeKeyClient.setCustomHttpHeader("Content-Type", "application/x-www-form-urlencoded");
HashMap<String, String> oneTimeKeyParam = new HashMap<>();
oneTimeKeyParam.put("application_name", "hello_app");
oneTimeKeyParam.put("key", "bb5eb953d3b41dcf59f4669d98f8e14782ed83133be772956b");
Vector<Object> params = new Vector<Object>();
params.add(oneTimeKeyParam);
oneTimeKeyClient.callAsync(new XMLRPCCallback() {
#Override
public void onResponse(long id, Object response) {
try {
result = ((Map) response).get(NAME_ONE_TIME_KEY).toString();
} catch (Exception e) {
Timber.e("onParseError %s", e.getMessage());
DialogUtil.showLoginErrorDialog(getSupportFragmentManager());
}
}
#Override
public void onError(long id, XMLRPCException error) {
Timber.e("onError %s", error.getMessage());
DialogUtil.showLoginErrorDialog(getSupportFragmentManager());
}
#Override
public void onServerError(long id, XMLRPCServerException error) {
Timber.e("onServerError %s", error.getMessage());
DialogUtil.showLoginErrorDialog(getSupportFragmentManager());
}
}, "", params);
} catch (Exception e) {
Timber.e("onError %s", e.getMessage());
DialogUtil.showLoginErrorDialog(getSupportFragmentManager());
}
I got error " onServerError APPLICATION_NAME must record not exists."
I using aXMLRPC library https://github.com/gturri/aXMLRPC .
Which library do you recommend ?
Can I use Retrofit to make xml-rpc request ?
Thanks for any help
You just use retrofit like this:
#FormUrlEncoded
#POST("onetime_key")
Observable<OneTimeKeyRes> requestOneTimeKey(#Field("application_name") String applicationName, #Field("key") String key);
You must add SimpleXmlConverter:
Retrofit retrofit = new Retrofit.Builder()
.client(builder.build())
.baseUrl(YOUR_BASE_URL)
.addConverterFactory(SimpleXmlConverterFactory.create())
.build();

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