unable to post array into server using retrofit - java

i am trying to post multiple images with array but i am not able to send it into server because its shows some error
when i am trying to send images converted into bitmap it goes into onFailure method and shows error like below
error returns bitmap
D/Onfail: /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCACKAIoDASIA
AhEBAxEB/8QAHgABAAIDAQADAQAAAAAAAAAAAAUIBgcJAwECBAr/xABSEAABAgIFAhEGCAsJAAAA
AAAEAAUDBgECBxQVESEIExgkJTE1QVFVV2FxlJXR1BYjNER1oRIXM0VUgZGWNzhDWGRlsbbF1fAm
NlNWpbXB4fH/xAAYAQEBAQEBAAAAAAAAAAAAAAAAAgQDBf/EACIRAQAABAYDAQAAAAAAAAAAAAAB
AxPhAkFhcpHBESGhcf/aAAwDAQACEQMRAD8A/toREWh44iIgIiICIiAiIgIiICIiAiIgIiICIiAi
IgIiwmd5/lGztqqPc4vENqDrxLqL5oqOcYR9FEFC2QN78ufaQZsirJqtrDePXX7uOng01W1hvHrr
93HTwaOdPX5dZtFWTVbWG8euv3cdPBpqtrDePXX7uOng0Kevy6zaKsmq2sN49dfu46eDWxbP7ZbO
bSiDA5Sfr4eHC02K3mClAHXf6UIIbnO3tvLv50dG1kREBERAREQEREBERAVDdE2KM620WDsjlBvj
U4OjOAe3kZdIjDmTQGGXm4HEHhp+tXyVEtEX+HvQ+e3ZW/fIVEyst0OmSWrEaGayUgMB+s0Y3J3c
BaSoTUzsDWRHgj0etF37DW8Kn3cFKyWy9j0N9qzQS6yxZ9LdSI3xbo6N7gwCwDhCM90vfDno28/7
VonRYWQT09TpUneWmR0mVrMa28AkdnFKdjm0gPNuSFr+47XRz051sjQjWVzdJAczz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83EnhwiOBmlDi6ZEy
eZHDpyiiiCepA/q/L9qyODaXO48euVBmQzTogoAEWmJCFj6cOz7k+mg5b83beIbq5s+ZBkMSRWkO
1iNIVeMYS1jvJAGmRIukH3e60mCil/p2fJRz56Fkkj2fyu4yu2zC9huZNeIBawfFGDKuN88j2pnM
abprL6cWXTRw5d5aTHenUV1qv0FyMqPUM/FMUvWvsQoLvl6veT077aefOtisdr81tppR7g5GOFeG
wzQzM0OHGFBgM7hMgtzxQQQILD/VBMjfky/ag2KyysyOUtupLPBiS6NPkpS+KU1kFX+hnIDtmlBn
oKELN9Rcd0NkaeMOlY4PJsrzPEPGl6W31sJlueJflyKPEehY8d9b3gt4vd7voVLeyvjdhOIcVdNL
bn1U4TjMjpEMjGPBFeuYA3tZUOHdYEDDgyhHgMUQQL0IFuODEcNjt/byr951os7uMZtJNmRxrxms
/GW+vDi6RHxjjQu5emnfrBxQbpIs3kgkVkmIOoPXAhtdpDo9M8tv7o7QHLyEa2gwQUR2egct+csW
2Ww6l0asKD2H59dWgENRUs2ZEs7UQyBkNU0RcPIKv0CER5UmXu6F0+o8HNvqEjWmz1GiAV68yGVK
7WeSe1XeEKPhpBgtzLulIQOsgXEHdZvyYU67fPTCvUzTDNMYPGXIh2jBwrqBDifIBj/RhBAvQgeF
v+xB3JlP+60sewWj/aw1kSx6WIdeDLctwY1SJUiQ2FnhRYcT8jsWH/39ealZCjOKNIbW0qJpxIAZ
Mb/EIFFjxsn9e7pyKSRBE4Ix8UNfUBe9MEY+KGvqAvepZEETgjHxQ19QF70wRj4oa+oC96lkQROC
MfFDX1AXvTBGPihr6gL3qWRBE4Ix8UNfUBe9MEY+KGvqAvepZEETgjH
this is my post method
private void PostInfo() {
bitmap = ((BitmapDrawable) defoult.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
ArrayList<String> filePaths = new ArrayList<>();
filePaths.add(imageString);
Log.d("strinimagess",imageString);
//filePaths.add("file:///storage/emulated/0/DCIM/Camera/IMG_20191207_131304.jpg");
// filePaths.add("file:///storage/emulated/0/DCIM/Camera/IMG_20191207_131300.jpgg");
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
builder.addFormDataPart("skill_years", nameField.getText().toString());
builder.addFormDataPart("skill_where", nameField1.getText().toString());
builder.addFormDataPart("about_work", nameField2.getText().toString());
builder.addFormDataPart("skill_id", skill_id);
builder.addFormDataPart("user_id", user_id);
for (int i = 0; i < filePaths.size(); i++) {
File file = new File(filePaths.get(i));
builder.addFormDataPart("skill_images", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
}
MultipartBody requestBody = builder.build();
jsonObject = new JsonObject();
jsonObject.addProperty("skill_years", nameField.getText().toString());
jsonObject.addProperty("skill_where", nameField1.getText().toString());
jsonObject.addProperty("about_work", nameField2.getText().toString());
jsonObject.addProperty("skill_id", skill_id);
jsonObject.addProperty("user_id", user_id);
jsonObject.addProperty("skill_images", String.valueOf(myImageList));
RetrofitInterface jsonpost = ServiceGenerator.createService(RetrofitInterface.class,"http://littletreasure.org.in/");
Call<InFo_Post> call = jsonpost.post(requestBody);
call.enqueue(new Callback<InFo_Post>() {
#Override
public void onResponse(Call<InFo_Post> call, retrofit2.Response<InFo_Post> response) {
if (response.isSuccessful()){
Log.d("response", String.valueOf(response.body().getMsg()));
Toast.makeText(Info.this, "success", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<InFo_Post> call, Throwable t) {
Log.d("Onfail",t.getMessage());
Toast.makeText(Info.this, "failed", Toast.LENGTH_SHORT).show();
}
});
this is my Info Post model class
public class InFo_Post {
private String status;
private String msg;
private DataModel data;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public DataModel getData() {
return data;
}
public void setData(DataModel data) {
this.data = data;
}
private class DataModel {
private String skill_years;
private String skill_where;
private String about_work;
private String skill_images;
public String getSkill_years() {
return skill_years;
}
public void setSkill_years(String skill_years) {
this.skill_years = skill_years;
}
public String getSkill_where() {
return skill_where;
}
public void setSkill_where(String skill_where) {
this.skill_where = skill_where;
}
public String getAbout_work() {
return about_work;
}
public void setAbout_work(String about_work) {
this.about_work = about_work;
}
public String getSkill_images() {
return skill_images;
}
public void setSkill_images(String skill_images) {
this.skill_images = skill_images;
}
}
}

i wrote a method that takes array of paths for images and return array of StringBase64
private ArrayList<String> imagesBase64(ArrayList<String> filePathes){
ArrayList<String> imagesBase64=new ArrayList<>();
for (int i = 0; i <filePathes.size() ; i++) {
Bitmap bm = BitmapFactory.decodeFile(filePathes.get(i));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
String imgString = Base64.encodeToString(b, Base64.NO_WRAP);
imagesBase64.add(imgString);
}
return imagesBase64;
}
but you must be sure your back-end receive array of Strings base64 to successfully upload it

Do you have just the bitmap or maybe you have also a file with that image ?
You can try create MultypartBody from data
private void sendFileToServer(String fileName) {
File file = new File(fileName);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
...
...
}
Also , don t forget in your WebService class to add annotation #Multipart at your post method

Make sure your API can handle a multiple files. Set your interface class with list of multipart files.
#Multipart
#POST("upload")
Call<ResponseBody> uploadMultipleFilesDynamic(
#Part("description") RequestBody description,
#Part List<MultipartBody.Part> files);
The second part of the implementation is using the new endpoint declaration and passing some files. Convert your files to multipart
#NonNull
private RequestBody createPartFromString(String descriptionString) {
return RequestBody.create(
okhttp3.MultipartBody.FORM, descriptionString);
}
#NonNull
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {
File file = FileUtils.getFile(this, fileUri);
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
file
);
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}
MultipartBody.Part is used to send also the actual file name.
List<MultipartBody.Part> parts = new ArrayList<>();
if (photoUri != null) {
parts.add(prepareFilePart("photo", photoUri));
}
RequestBody description = createPartFromString("hello, this is description speaking");
// create upload service client
FileUploadService service = ServiceGenerator.createService(FileUploadService.class);
// finally, execute the request
Call<ResponseBody> call = service.uploadMultipleFilesDynamic(description, parts);
call.enqueue(...);
You can refer this official link : https://futurestud.io/tutorials/retrofit-2-how-to-upload-a-dynamic-amount-of-files-to-server

Related

Need to get a string from response returned by api using retrofit2

I am trying to get string value returned by API on success. I am getting success but I do not getting the required value in the response, but when I navigate to response-> body-> responseBody then it shows me that value but I am unable to get that value (please check screen shot for detail).
private void uploadImage(String imagePath) {
try{
showProgressDialogue();
File file = new File(imagePath);
RequestBody photoContent = RequestBody.create(MediaType.parse("multipart/form data"), file);
MultipartBody.Part photo = MultipartBody.Part.createFormData("file",file.getName(),photoContent);
//RequestBody description = RequestBody.create(MediaType.parse("description"),"abc");
UploadService uploadService = APIClient.getClient().create(UploadService.class);
Call call1 = uploadService.UploadOMRExamPaper(photo);
call1.enqueue(new Callback<Response>() {
#Override
public void onResponse(Call<Response> call, Response<Response> response) {
progressBar.dismiss();
}
#Override
public void onFailure(Call<Response> call, Throwable t) {
progressBar.dismiss();
Toast.makeText(getApplicationContext(), t.getMessage(),Toast.LENGTH_LONG).show();
}
});
}catch (Exception e){
progressBar.dismiss();
Toast.makeText(this, e.getMessage(),Toast.LENGTH_LONG).show();
}
}
Change your code:
From:
File file = new File(imagePath);
RequestBody photoContent = RequestBody.create(MediaType.parse("multipart/form data"), file);
MultipartBody.Part photo = MultipartBody.Part.createFormData("file",file.getName(),photoContent);
To:
File file = new File(imagePath);
RequestBody photoContent = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part photo = MultipartBody.Part.createFormData("upload", file.getName(), photoContent );
Note:"upload" is just example here,you should write there from your api paramater.

Why the String inside Controller not printing anything?

I am trying to send Image and Id using retrofit for that i am sending Multipart file and String.
This is my Upload Method on Android side ->
private void UploadFiles() {
File uploadFile = fileArrayList.get(0);
if (uploadFile != null) {
Log.d(TAG, "UploadFiles: File Name is -> " + uploadFile.getName());
// Parsing any Media type file
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), uploadFile);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part cropImage = MultipartBody.Part.createFormData("cropImage", uploadFile.getName(), requestFile);
RequestBody cropId = RequestBody.create(MediaType.parse("multipart/form-data"), uploadFile.getParentFile().getName());
Api.uploadCropImage(cropImage,cropId, new Callback<BasicResponse>() {
#Override
public void onResponse(Call<BasicResponse> call, Response<BasicResponse> response) {
if (response.body() != null) {
Log.d(TAG, "onResponse: Success" + response.body().getResponse());
}
else{
Log.d(TAG, "onResponse: null Response");
}
}
#Override
public void onFailure(Call<BasicResponse> call, Throwable t) {
Log.d(TAG, "onResponse: Failure");
}
});
}
}
My Upload CropImage Method ->
public static void uploadCropImage(MultipartBody.Part multipartBody,RequestBody cropId,
Callback<BasicResponse> callback) {
UploadCropImageApi uploadCropImageApi = retrofit.create(UploadCropImageApi.class);
Call<BasicResponse> call = uploadCropImageApi.uploadCropImage(multipartBody,cropId);
call.enqueue(callback);
}
My Interface ->
public interface UploadCropImageApi {
#Multipart
#POST(UPLOAD_FILE_TO_AWS_URL)
Call<BasicResponse> uploadCropImage(#Part MultipartBody.Part cropImage, #Part("cropId") RequestBody cropId);
}
This is my Spring Controller, What's wrong with it? It's not printing cropId.
#RequestMapping(value = "/UploadCropImage", method = RequestMethod.POST, consumes = {"multipart/form-data"})
#ResponseBody
public String UploadImage(#RequestBody MultipartFile cropImage,#RequestBody String cropId ,HttpServletRequest request) {
System.out.println("String is -> " + cropId);
return null;
}
You cannot use two #RequestBody as it can bind to a single object only (the body can be consumed only once)
You need to use #RequestParam String cropId instead of RequestBody.
See here for clarification
UPDATE :Here is your controller method look like
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public #ResponseBody ResponseEntity<GenericResponseVO<? extends IServiceVO>> uploadFileHandler(#RequestParam("name") String name, #RequestParam("file") MultipartFile file,HttpServletRequest request, HttpServletResponse response) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath() + File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
System.out.println("Server File Location=" + serverFile.getAbsolutePath());
return null;
} catch (Exception e) {
return null;
}
}
}

Uploading image by using Retrofit

I've been trying to upload an image from my application through API. But I keep getting this as response:
{"error":"<p>You did not select a file to upload.<\/p>"}
This is my code:
APIService.java
#Multipart
#POST("/media/upload.html")
Call<UploadImg> uploadimage (#Part MultipartBody.Part file);
UploadImageActivity.java
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
Uri uri = data.getData();
Picasso.with(this).load(uri).fit().into(btn_img_picker);
String imagePath;
if (data.toString().contains("content:")) {
imagePath = getRealPathFromURI(uri);
} else if (data.toString().contains("file:")) {
imagePath = uri.getPath();
} else {
imagePath = null;
}
File file = new File(imagePath);
System.out.println(imagePath);
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("userfile", file.getName(), requestFile);
System.out.println(file.getName());
Call<UploadImg> call = mAPIService.uploadimage(body);
call.enqueue(new Callback<UploadImg>() {
#Override
public void onResponse(Call<UploadImg> call, Response<UploadImg> response) {
System.out.println(response.raw());
}
#Override
public void onFailure(Call<UploadImg> call, Throwable t) {
System.out.println(t);
}
});
}
}
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = getContentResolver().query(contentUri, proj, null, null,
null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
I have tested sending image in Postman's form-data. I can send a picture from my desktop and received intended response. But I can't do the same with my code in android.
Am I sending the incorrect path format of the image? Currently, variable imagePath has an output like this:
/storage/emulated/0/Download/download.jpg
If this is the incorrect path to send, please tell the correct one. Thanks in advance.
try this
#Multipart #POST("user/updateprofile") Observable<ResponseBody>
updateProfile(#Part("user_id") RequestBody id, #Part("full_name")
RequestBody fullName, #Part MultipartBody.Part image, #Part("other")
RequestBody other);
pass it like this
File file = new File("/storage/emulated/0/Download/Corrections 6.jpg"); RequestBody
requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
add another part within the multipart request
RequestBody fullName = RequestBody.create( MediaType.parse("multipart/form-data"), "Your Name");
service.updateProfile(id, fullName, body, other)
You can use below code for uploading image
First you write code for calling request
//profile pic is image path
RequestBody imagePath = Utility.imageToBody(profilePic);
TestApiInterface service = WebServiceCaller.getClient();
Call<SuccessResponse> call = service.mediaUpload(imagePath);
call.enqueue(new Callback<SuccessResponse>() {
#Override
public void onResponse(Call<SuccessResponse> call,
Response<SuccessResponse> response) {
SuccessResponse result;
if (response.isSuccessful()) {
result = response.body();
}
}
#Override
public void onFailure(Call<SuccessResponse> call, Throwable t) {
}
});
Then you write code for API
#Multipart
#POST("user/mediaupload")
Call<SuccessResponse> mediaUpload(#Part("media_file\"; filename=\"test_media.png\" ") RequestBody media_file);
Then code for Imagetobody covert is below
public static RequestBody imageToBody(String text) {
RequestBody requestBody;
if (text != null && text.length() > 0) {
MediaType MEDIA_TYPE = MediaType.parse("image/*");
File file = new File(text);
requestBody = RequestBody.create(MEDIA_TYPE, file);
} else {
requestBody = null;
}
return requestBody;
}
Try this I had another way to implement
Inside your interface
#Multipart
#POST("edit_profile")
Call<TokenResponse> getTokenAccess(#PartMap Map<String, RequestBody> map);
Call in your Activity
private void getData() {
Retrofit retrofit=new Retrofit.Builder()
.baseUrl("your_base_url_here")
.addConverterFactory(GsonConverterFactory.create())
.build();
Click service=retrofit.create(Click.class);
File file = new File("/storage/sdcard0/Pictures/OGQ/Puskinn Sharma_Jump roof skyscraper_YkRiRWpYcw.jpg");
//make sure your image path is valid
String convert_File_2String= String.valueOf(file);
String fileNAme=convert_File_2String.substring(convert_File_2String.lastIndexOf("/")+1);
RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "Sunil");
RequestBody id = RequestBody.create(MediaType.parse("text/plain"), "56");
RequestBody lastname= RequestBody.create(MediaType.parse("text/plain"), "Kumar");
Map<String, RequestBody> map = new HashMap<>();
map.put("profile_pic\"; filename=\""+fileNAme+"\" ", fbody);
map.put("firstname", name);
map.put("user_id", id);
map.put("lastname",lastname);
Call<TokenResponse> tokenResponseCall=service.getTokenAccess(map);
tokenResponseCall.enqueue(new Callback<TokenResponse>() {
#Override
public void onResponse(Call<TokenResponse> call, Response<TokenResponse> response) {
TokenResponse tokenResponse=response.body();
Log.e("93","MA>>"+tokenResponse.getJwt());
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<TokenResponse> call, Throwable throwable) {
Log.e("172","><<>>"+throwable);
Log.e("TAG", "onFailure: 173"+call.toString() );
}
});
}

Images(base64) not uploading correctly

Unfortunately I'm facing some issues when I try to upload some images from an android device to a database.
The images are in a folder. This folder contains images as well as other stuff. I don't know the names of the images and I need to upload only the images(jpg). Before I upload the images I need to encode them with base64.
First I get the jpg files from the folder. Then I get the ID out of the image name. After that I encode it via base64:
Button upload = (Button) findViewById(R.id.upload);
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
String path = Environment.getExternalStorageDirectory().getPath();
File dir = new File(path);
File[] files = dir.listFiles();
for (int i = 0; i < files.length; ++i) {
if (files[i].getName().endsWith(".jpg")) {
pics = new File(String.valueOf(files[i]));
id = String.valueOf(files[i]);
String sub = id.substring(id.lastIndexOf("/") + 1);
int index = sub.indexOf("_");
String book;
if (index >= 0) {
book = sub.substring(0, index);
ID = book;
Log.e("ID", ID);
}
Bitmap imagex = BitmapFactory.decodeFile(pics.getAbsolutePath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imagex.compress(Bitmap.CompressFormat.JPEG, 70, baos);
byte[] b = baos.toByteArray();
Image = Base64.encodeToString(b, Base64.DEFAULT);
try {
new HttpAsyncTask(ID,Image,Nummer).execute("https://....");
} catch (Exception e) {
Log.e("InputStream", e.getMessage());
}
Log.e("PICS", id);
}
}
}
});
public String POST(String url) {
InputStream inputStream;
try {
HttpClient httpclient = classxy.getNewHttpClient();
HttpPost httpPost = new HttpPost(url);
String json = "";
JSONObject jsonObject = new JSONObject();
jsonObject.put("bookId", ID);
jsonObject.put("imageString", Image);
jsonObject.put("imageNumber", Nummer);
json = jsonObject.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Apikey", data);
httpPost.setHeader("Modul", "upload_image");
HttpResponse httpResponse = httpclient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null)
result = classxy.convertInputStreamToString(inputStream);
else
result = "Fehler!";
} catch (Exception e) {
Log.e("InputStream", e.getLocalizedMessage());
}
int num = Integer.parseInt(Nummer);
num++;
Nummer = Integer.toString(num);
return result;
}
public class HttpAsyncTask extends AsyncTask<String, Void, String> {
private final Object ID, Image, Nummer;
public HttpAsyncTask(Object ID, Object Image, Object Nummer) {
this.ID = ID;
this.Image = Image;
this.Nummer = Nummer;
}
protected String doInBackground(String... urls) {
return POST(urls[0]);
}
protected void onPostExecute(String result) {
if (result.matches("(.*)false(.*)")) {
Toast.makeText(getApplicationContext(), "....", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "...", Toast.LENGTH_SHORT).show();
}
Log.e("RESPONSE", result);
}
}
It does encode the images via base64 and it does upload some of the images. Unfortunately it uploads only the first image or one image multiple times. It never uploads the correct amount of images in the correct order. I've been sitting on this problem for a while now and can't figure out what I'm doing wrong.
Can you tell me what I'm doing wrong?
Your program doesn't seem to be thread-safe at all.
Your fields ID, Image and Nummer are updated with every iteration of the for loop. Most likely the loop has already finished before POST runs for the first time. Your observation would support this assumption:
Unfortunately it uploads only the first image or one image multiple times.
You can observe this by logging every access to these fields. You'll find, that it's not alternating like you expect it to be.
Therefore you should implement everything without using these fields at all. Instead use local variables and pass these around. Using the Nummer field could be usefull if you want to use it for more than one upload. But it might be better to use an int directly:
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
String ID = "", Image;
int Nummer = 0;
[...]
for (int i = 0; i < files.length; ++i) {
if (files[i].getName().endsWith(".jpg")) {
[...]
try {
new HttpAsyncTask(ID,Image,Integer.toString(Nummer++)).execute("https://....");
} catch (Exception e) {
Log.e("InputStream", e.getMessage());
}
Log.e("PICS", id);
}
}
}
});
public String POST(String url, String ID, String Image, String Nummer) {
InputStream inputStream;
try {
[...]
} catch (Exception e) {
Log.e("InputStream", e.getLocalizedMessage());
}
//int num = Integer.parseInt(Nummer);
//num++;
//Nummer = Integer.toString(num);
return result;
}
public class HttpAsyncTask extends AsyncTask<String, Void, String> {
private final String ID, Image, Nummer;
public HttpAsyncTask(String ID, String Image, String Nummer) {
this.ID = ID;
this.Image = Image;
this.Nummer = Nummer;
}
protected String doInBackground(String... urls) {
return POST(urls[0], ID, Image, Nummer);
}
protected void onPostExecute(String result) {
[...]
}
}
In My suggestion Dont call Asynctask directly from for loop because there are no any monitor on we can set for which image selected.
So Go through below steps:
1) In for loop get all images ID,Name and number and store it to ArrayList
2) Check ArrayList first is empty or not
if not then get first position ID, Image and number
call new HttpAsyncTask(ID,Image,Integer.toString(Nummer++)).execute("https://....");
3) In HttpAsyncTask onPostExecute(String result) method
first remove first position data
then create
for loop (i=0;i<ArrayList.Size();i++) {
ID=ArrayList first position data ID
Image=ArrayList first position data IMAGE
number=ArrayList first position data number
Call new HttpAsyncTask(ID,Image,Integer.toString(Nummer++)).execute("https://....");
}
So here first Image send by then after second then after third up to your list not empty and every time different image selected.
Thats it...

Display image stored as blob using GWT Jersy Rest

I am not able to display an image stored as blob returned by a rest service :
This is the rest service code that returns the blob stored image coded into base64 :
#GET
#Path("/get")
#Produces("image/jpeg")
public Response getFile() {
String base64 = getStringImage();
ResponseBuilder response = Response.ok((Object) base64);
return response.build();
}
String getStringImage() {
try {
AnounceService anounceService = (AnounceService)getApplicationContext().getBean("AnounceService");
Blob imageBlob = anounceService.getStgImage();
int blobLength = (int)imageBlob.length();
byte[] buff = imageBlob.getBytes(1, blobLength);
String base64=Base64Utils.toBase64(buff);
return base64;
} catch (Exception exc) {
}
return null;
}
This is the gwt client code that fails to display the image returned by the above rest code :
String url = "root/api/image/get";
final RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);Image img;
builder.setCallback(new RequestCallback() {
public void onResponseReceived(final Request request, final Response response) {
if (response.getStatusCode() == Response.SC_OK) {
final HTML imageHolder = new HTML();
String base64 = response.getText();
String imgTag = "<img src='data:image/gif;base64,"+base64+"' />'";
imageHolder.setHTML(imgTag);
RootPanel.get().add(imageHolder);
}
}
There is no error triggered, but I don't see any image displayed in the browser.

Categories