Uploading image from Android to server with okhttp multipart - android

Here is how I get the image from photo library:
private void presentPhotoSelector() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == Activity.RESULT_OK && data != null) {
mSelectedPhotoUri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), mSelectedPhotoUri);
photoCircleImageView.setImageBitmap(bitmap);
photoCircleImageView.setVisibility(View.VISIBLE);
selectPhotoButton.setVisibility(View.INVISIBLE);
uploadImageToServer(mSelectedPhotoUri);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is how I try to upload it:
public class JSONResponse {
boolean userUploadedProfileImage;
User user;
}
private void uploadImageToServer(Uri selectedPhotoUri) {
if (selectedPhotoUri == null) {
Log.d(TAG, "uploadImageToServer: selectedPhotoUri is null");
return;
}
if (!AuthService.getInstance(mContext).isLoggedIn()) {
Log.d(TAG, "uploadImageToServer: User not logged in");
return;
}
showLoading("Laster opp bilde...", "Vennligst vent mens prosess foregÄr");
File file = new File(selectedPhotoUri.getPath());
final MediaType MEDIA_TYPE_JPG = MediaType.parse("image/jpeg");
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", "image.jpg",
RequestBody.create(MEDIA_TYPE_JPG, file))
.build();
Request request = new Request.Builder()
.header("Authorization", "Bearer " + AuthService.getInstance(mContext).getToken())
.url(Config.URL + "/api/user/upload-profile-image")
.post(requestBody)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
hideLoading();
}
});
Log.d(TAG, "onFailure: response failed: " + e.getLocalizedMessage());
}
#Override
public void onResponse(Call call, Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
hideLoading();
}
});
String responseBodyString = response.body().string();
Log.d(TAG, "onResponse: responseBodyString: " + responseBodyString);
Gson gson = new Gson();
SettingsFragment.JSONResponse jsonResponse = gson.fromJson(responseBodyString, SettingsFragment.JSONResponse.class);
if (jsonResponse != null) {
UserService.getInstance(mContext).setMyUser(jsonResponse.user);
Log.d(TAG, "onResponse: jsonResponse.userUploadedProfileImage: " + jsonResponse.userUploadedProfileImage);
Log.d(TAG, "onResponse: jsonResponse.user: " + jsonResponse.user.toString());
}
}
});
}
This does not work, the loader never stops spinning and on server side I get this error: multipart: NextPart: client disconnected
However, if I change the code above from:
File file = new File(selectedPhotoUri.getPath());
to:
String file = selectedPhotoUri.getPath();
Then request is successful, however, when I try to open the image on a browser it says "the image cannot be displayed because it contains errors". When I look at the database I can see that it interpreted its mime type as: application/octet-stream, and not image/jpeg.
I am stuck and I don't know what to do.
I am now getting this error on console: onFailure: response failed: /-1/1/content:/media/external/images/media/69/ORIGINAL/NONE/656735600 (No such file or directory)
I am running this on a simulator, if that helps.

One way is:
You have to convert Bitmap to Base64(String) and send that base64 to server.

Related

Upload File via WordPress REST API from Android Application

I am trying to upload a file to WordPress using REST API. I have tried different headers, values but no luck. I have tried different clients such as okhttp and custom one such as Fast-AndroidNetworking.
I have succeeded to create new post with AndroidNetworking, but when it comes to creating/uploading new media, it does not work and does not return any response.
No luck to upload.
Following my code with AndroidNetworking.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnImage = findViewById(R.id.button);
btnImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 1234);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ImageView imgTestImage = findViewById(R.id.imageView1);
final TextView txtTestPath = findViewById(R.id.txtTestPath);
if (resultCode == Activity.RESULT_OK)
switch (requestCode){
case 1234:
Uri uriSelectedImage = data.getData();
String imgFullPath = uriSelectedImage.getPath();
String imgPath = imgFullPath.substring(imgFullPath.lastIndexOf(":")+1);
File imgFile = new File(imgPath);
String imgName = imgFile.getName();
long imgSize = imgFile.length();
String mimType = getContentResolver().getType(uriSelectedImage);
txtTestPath.setText(imgPath +"\n"+mimType + "\n"+ imgName + " "+ String.valueOf(imgSize));
AndroidNetworking.initialize(getApplicationContext());
AndroidNetworking.post("https://test.matjri.com/wp-json/wp/v2/media")
.addFileBody(imgFile)
.addHeaders("Connection", "keep-alive")
.addHeaders("Host", "test.matjri.com")
.addHeaders("Content-Length", String.valueOf(imgSize))
.addHeaders("Cache-Control", "no-cache")
.addHeaders("Content-Type", mimType)
.addHeaders("Content-Disposition", "attachment;filename=\"" + imgName + "\"")
.addHeaders("Authorization", "Bearer mytoken")
.setTag("uploadFile")
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
txtTestPath.setText(response.toString());
}
#Override
public void onError(ANError anError) {
txtTestPath.setText(anError.getMessage());
}
});
imgTestImage.setImageURI(uriSelectedImage);
}
}
}
I have also tried the okhttp instead of AndroidNetworking still no luck to upload, however, I get unknown errors.
The code with okhttp
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnImage = findViewById(R.id.button);
btnImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 1234);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ImageView imgTestImage = findViewById(R.id.imageView1);
final TextView txtTestPath = findViewById(R.id.txtTestPath);
if (resultCode == Activity.RESULT_OK)
switch (requestCode){
case 1234:
Uri uriSelectedImage = data.getData();
String imgFullPath = uriSelectedImage.getPath();
String imgPath = imgFullPath.substring(imgFullPath.lastIndexOf(":")+1);
File imgFile = new File(imgPath);
String imgName = imgFile.getName();
long imgSize = imgFile.length();
String mimType = getContentResolver().getType(uriSelectedImage);
txtTestPath.setText(imgPath +"\n"+mimType + "\n"+ imgName + " "+ String.valueOf(imgSize));
OkHttpClient okHttpClient = new OkHttpClient();
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
builder.addFormDataPart("file", imgPath);
String url = "https://test.matjri.com/wp-json/wp/v2/media/";
RequestBody fileBody = RequestBody.create(MediaType.parse(mimType), imgPath);
builder.addFormDataPart("file", imgName, fileBody);
RequestBody requestBody = builder.build();
Request request = new Request.Builder()
.url(url)
.addHeader("Authorization", "Bearer mytoken")
.addHeader("Content-Type", mimType)
.addHeader("Content-Length", String.valueOf(imgSize))
.addHeader("Content-Disposition", "attachment; filename=\"maroof.png\"")
.post(requestBody)
.build();
okHttpClient.newCall(request).enqueue(new okhttp3.Callback(){
#Override
public void onFailure(Call call, IOException e) {
Log.e("OkHttp1", "onFailure: "+e.toString());
}
#Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
if (body != null) {
txtTestPath.setText(body.string());
} else {
Log.e("OkHttp1", "onResponse: null");
}
}
});
imgTestImage.setImageURI(uriSelectedImage);
}
}
}
With PostMan the media is upload without any problem, and following is the code generated from PostMan.
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("file","/C:/Users/Abdul/OneDrive - OkamKSA/Alahdal/Personal/Web/SS/maroof.png",
RequestBody.create(MediaType.parse("application/octet-stream"),
new File("/C:/Users/Abdul/OneDrive - OkamKSA/Alahdal/Personal/Web/SS/maroof.png")))
.build();
Request request = new Request.Builder()
.url("https://test.matjri.com/wp-json/wp/v2/media")
.method("POST", body)
.addHeader("Authorization", "Bearer mytoken")
.addHeader("Cookie", "wp-wpml_current_admin_language_d41d8cd98f00b204e9800998ecf8427e=ar; _mcnc=1")
.build();
Response response = client.newCall(request).execute();
First of all, it is not the fault of AndroidNetworking, it is the permission denied, which I figured out after testing Retrofit, Retrofit throws the error for the permission denied which led me to fix the problem.
I checked above code after fixing the permission and it works very well.
Thank you
PS. There is no need for all the headers, token & Content-Disposition is enough.

Can Any one knows how to post image array to server in android?

I'm entangled in a query in which I need to send an image array to server.
I googled it but I couldn't find any relevant data, so can any one tell me how can I achieve it?
Early reply is appreciable .
My code is
private void imageUpload(final ArrayList imagePath) {
SimpleMultiPartRequest smr = new SimpleMultiPartRequest(
Request.Method.POST, BASE_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d( "Response", response );
try {
JSONObject jObj = new JSONObject( response );
String message = jObj.getString( "message" );
System.out.println( "Done" );
Toast.makeText( getApplicationContext(), message, Toast.LENGTH_LONG ).show();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText( getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG ).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
for (int i = 0; i<imagePath.size();i++){
String ab = imagePath.get( i ).toString();
System.out.println("Images is find path "+ab);
smr.addFile(""+i,imagePath.get(i).toString());
}
MyApplication.getInstance().addToRequestQueue(smr);
}
Thanks
I am using https://github.com/esafirm/android-image-picker this library to get images list
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.upload_btn:
openImagesList();
break;
}
}
public void openImagesList() {
ImagePicker.create(this) // Activity or Fragment
.start();
}
#Override
public void onActivityResult(int requestCode, final int resultCode, Intent data) {
if (ImagePicker.shouldHandle(requestCode, resultCode, data)) {
// Get a list of picked images
List<Image> images = ImagePicker.getImages(data);
List<File> imgFile = new ArrayList<>();
for (Image imge : images) {
imgFile.add(new File(imge.getPath()));
}
for (File f : imgFile) {
if (f.exists()) {
Log.i(TAG, "exist");
}
}
uploadToSever(imgFile);
}
super.onActivityResult(requestCode, resultCode, data);
}
Use https://github.com/amitshekhariitbhu/Fast-Android-Networking to POST request
public void uploadToSever(List<File> imgList) {
AndroidNetworking.upload("your sever url")
.addMultipartFileList("image[]", imgList)
.addMultipartParameter("key", "value")
.setPriority(Priority.HIGH)
.build()
.setUploadProgressListener(new UploadProgressListener() {
#Override
public void onProgress(long bytesUploaded, long totalBytes) {
// do anything with progress
}
})
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
// do anything with response
}
#Override
public void onError(ANError error) {
// handle error
}
});
}

Spring upload file using retrofit 2.1.0

I'm using spring for a backend and retrofit for rest client.
I want to upload a file
backend code
#PostMapping("/upload")
public ResponseEntity<String> handleFileUpload(#RequestParam("file") MultipartFile file, Model model) {
String name = null;
try {
storageService.store(file);
model.addAttribute("message", "You successfully uploaded " + file.getOriginalFilename() + "!");
files.add(file.getOriginalFilename());
name = files.get(files.size()-1).toString();
System.err.println(name.toString());
} catch (Exception e) {
model.addAttribute("message", "FAIL to upload " + file.getOriginalFilename() + "!");
}
return new ResponseEntity<String>(file.getOriginalFilename() , HttpStatus.OK);
}
function store
public void store(MultipartFile file) {
try {
Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
} catch (Exception e) {
throw new RuntimeException("FAIL!");
}
}
android code to select and upload file
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = ImagePicker.getImageFromResult(getActivity(), requestCode, resultCode, data);
if (bitmap != null) {
image.setImageBitmap(bitmap);
selection=data.getData();
String[] filepath={MediaStore.Images.Media.DATA};
Cursor cursor=getActivity().getContentResolver().query(selection,filepath,null,null,null);
cursor.moveToFirst();
int column=cursor.getColumnIndex(filepath[0]);
String path=cursor.getString(column);
File file =new File(path);
RequestBody requestfile = RequestBody.create(MediaType.parse("multipart/form-data"),file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image" , file.getName() , requestfile);
upload(body);
}
upload function
public void upload(MultipartBody.Part path){
Call<ResponseBody> callUploader = iBackEndService.uploadAttachment(path);
callUploader.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d(TAG,"UPLODER REUSSI" +" "+response.message());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable throwable) {
Log.e(TAG,throwable.getMessage());
}
});
}
Retrofit mapping (I'm using Retrofit 2.1.0)
#Multipart
#POST("upload")
Call<ResponseBody> uploadAttachment(#Part MultipartBody.Part filePart);
my upload function jump to onResponse but the file was not upload

How to upload image with Retrofit Android?

I have a function to request upload image with Retrofit like this
void uploadPhoto(File file) {
RequestBody photo = RequestBody.create(MediaType.parse("application/image"), file);
RequestBody body = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart("photo", file.getName(), photo)
.build();
fragment.showProgressDialog(fragment.loading);
fragment.getApi().uploadPhoto(PrefHelper.getString(PrefKey.TOKEN), body)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Observer<GenericResponse>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
fragment.dismissProgressDialog();
Timber.e(e.getMessage());
}
#Override
public void onNext(GenericResponse response) {
fragment.dismissProgressDialog();
if (response.getCode() == 1) {
fragment.showSuccessDialog("Saving success", false);
userInfo();
}
}
});
}
and for the example, I have a button to upload image in my fragment
#OnClick(R.id.btnChangePicture)
void onChangePictureClicked() {
}
What code should i put in
OnChangePictureClicked
So i can choose an image from gallery and then I request it to API.
void uploadPhoto(File file)
Thanks
Transform your image to an array of bytes and then create an Object Dto like the example below and send it to the server through Retrofit.
#Data
public class SetProfileImageRequestDto {
#SerializedName("Token")
private String token;
#SerializedName("Stream")
private byte[] image;
}
Retrofit Api Service:
#POST("SetProfileImage/")
Observable<ResultResponseDto> setProfileImage(#Body SetProfileImageRequestDto profileImageRequestDto);
Hope it works.
Create a Uri object in Activity or fragment.
private Uri selectedImage;
After that, You will get gallery result in onActivityResult.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
selectedImage = data.getData();
}
}
Then in your onChangePictureClicked method.
#OnClick(R.id.btnChangePicture)
void onChangePictureClicked() {
if(selectedImage !=null){
uploadPhoto(new File(selectedImage.getPath()));
}
}
You can use multipart with retrofit please look this example of image upload using retrofit, its best for you.
its working for me.
//Create Upload Server Client
ApiService service = RetroClient.getApiService();
//File creating from selected URL
File file = new File(imagePath);
// create RequestBody instance from file
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body =
MultipartBody.Part.createFormData("uploaded_file", file.getName(), requestFile);
Call<Result> resultCall = service.uploadImage(body);
resultCall.enqueue(new Callback<Result>() {
#Override
public void onResponse(Call<Result> call, Response<Result> response) {
progressDialog.dismiss();
// Response Success or Fail
if (response.isSuccessful()) {
if (response.body().getResult().equals("success"))
Snackbar.make(parentView, R.string.string_upload_success, Snackbar.LENGTH_LONG).show();
else
Snackbar.make(parentView, R.string.string_upload_fail, Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(parentView, R.string.string_upload_fail, Snackbar.LENGTH_LONG).show();
}
/**
* Update Views
*/
imagePath = "";
textView.setVisibility(View.VISIBLE);
imageView.setVisibility(View.INVISIBLE);
}
#Override
public void onFailure(Call<Result> call, Throwable t) {
progressDialog.dismiss();
}
});
http://www.pratikbutani.com/2016/06/android-upload-image-file-using-retrofit-2-0/

My ProgressDialog is Not Disappearing

I am working on a project in android to upload a file to server using file chooser But there is a problem, when i am Uploading more than 500 kB file. The file is uploaded but My Progress Dialog is not disappearing and if i uploaded file 100 KB it's uploaded to server and i got a message file uploaded successfully. But I'm not able to get server response if i uploaded more than 500 kB file. Please Help me. Thank You.
It's my UploadFile() Methods
private void uploadFile() {
dialog = ProgressDialog.show(getActivity(), "", "Uploading File...", true);
// Map is used to multipart the file using okhttp3.RequestBody
Map<String, RequestBody> map = new HashMap<>();
long maxLength = 10000000;
File file = new File(selectedFilePath);
if(file.length() > maxLength){
Toast.makeText(getActivity(), "can't upload file if size more than 10mb", Toast.LENGTH_LONG).show();
dialog.dismiss();
}else {
String name = tv_name.getText().toString();
String email = tv_email.getText().toString();
// Parsing any Media type file
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
RequestBody requestBody1 = RequestBody.create(MediaType.parse("text/plain"), name);
RequestBody requestBody2 = RequestBody.create(MediaType.parse("text/plain"), email);
map.put("file\"; filename=\"" + selectedFilePath + "\"", requestBody);
map.put("name\"; username=\"" + name + "\"", requestBody1);
map.put("email\"; email=\"" + email + "\"", requestBody2);
ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
Call<ServerResponse> call = getResponse.upload("token", map);
call.enqueue(new Callback<ServerResponse>() {
#Override
public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
ServerResponse serverResponse = response.body();
if (serverResponse != null) {
if (serverResponse.getSuccess()) {
Toast.makeText(getActivity(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
// Log.v("Response", serverResponse.toString());
}
dialog.dismiss();
goToProfile();
}
#Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
}
});
}
}
When you get response you have to dismiss your progress dialog.
Example:
if (cls_networlconnection.isOnline())
{
progressdialog = ProgressDialog.showdialog(this,"Loading");
APICall();
}
else {
Toast.makeText(getApplicationContext(),UserToastMessage.NETWORKCONNECTION, Toast.LENGTH_LONG).show();
callNoconnection();
}
API Call Success()
{
if(progressDialog.isShowing)
progressDialog.dismiss();
//your logic
}
Update your onFailure code :
#Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
dialog.dismiss();
}
Also in onResponse, first you need to dismiss dialog :
#Override
public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
if(progressDialog.isShowing){
dialog.dismiss();
}
ServerResponse serverResponse = response.body();
if (serverResponse != null) {
if (serverResponse.getSuccess()) {
Toast.makeText(getActivity(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
// Log.v("Response", serverResponse.toString());
}
goToProfile();
}

Categories

Resources