Android camera image not uploaded to server . Using Multipart data Http post - android

I am trying to upload image from camera and gallery using multipart data http post using volley, but the image taken from camera is not getting uploaded whereas from the gallery is uploaded.
private void startCamera() {
Intent imageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(imageIntent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode) {
case CAMERA_CAPTURE_IMAGE_REQUEST_CODE:
if(resultCode== Activity.RESULT_OK){
previewCapturedImage();
}else{
Toast.makeText(getActivity(),"User cancelled image capture", Toast.LENGTH_SHORT).show();
}
break;
}
private void previewCapturedImage() {
try {
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
filePath=fileUri.getPath();
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, options.outWidth, options.outHeight, matrix, true);
postImageView.setImageBitmap(rotatedBitmap);
((TextView)appView.findViewById(R.id.deleteBtn)).setVisibility(View.VISIBLE);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
public void postFeed(String commentString){
RequestQueue mqueue = Volley.newRequestQueue(getActivity());
Map<String, String> params = new HashMap<String, String>();
params.put("text",commentString);
params.put("user_id",SettingsHelper.getInstance(getActivity()).getPreference("id"));
TSUServerRequest.postFeed(getActivity(),mqueue,params,new File(filePath),new Response.Listener<String>() {
#Override
public void onResponse(String s) {
Log.d("a","bscljk");
filePath="";
fileUri= null;
//Toast.makeText(getActivity(),"Success",Toast.LENGTH_LONG).show();
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
volleyError.printStackTrace();
}
});
public static void postFeed(Context context,RequestQueue queue,Map<String, String> params,File file,
Listener<String> listener, ErrorListener errorListener){
if (TSUServerRequest.checkForConnection(context)) {
String url =API_CREATE_POST;
MultiPartRequest myReq = new MultiPartRequest(url,errorListener,listener,file,params);
queue.add(myReq);
queue.start();
}else{
Toast.makeText(context, "No Internet!Please try again!", Toast.LENGTH_LONG).show();
}
}
////MultipartRequest.java
public class MultiPartRequest extends Request<String> {
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
HttpEntity httpentity;
private static final String FILE_PART_NAME = "picture";
private final Response.Listener<String> mListener;
private final File mFilePart;
private final Map<String, String> mStringPart;
public MultiPartRequest(String url, Response.ErrorListener errorListener,
Response.Listener<String> listener, File file,
Map<String, String> mStringPart) {
super(Method.POST, url, errorListener);
mListener = listener;
mFilePart = file;
this.mStringPart = mStringPart;
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
buildMultipartEntity();
}
public void addStringBody(String param, String value) {
mStringPart.put(param, value);
}
private void buildMultipartEntity() {
entity.addPart(FILE_PART_NAME, new FileBody(mFilePart));
for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
entity.addTextBody(entry.getKey(), entry.getValue());
}
}
#Override
public String getBodyContentType() {
return httpentity.getContentType().getValue();
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
httpentity = entity.build();
httpentity.writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
return Response.success("Uploaded", getCacheEntry());
}
#Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
}

The reason image was not getting uploaded was size.
Image file immediately taken from camera is too big in size and hence needs to be compressed.
The same file when picked from gallery gets uploaded because gallery internally compresses the files.
public File compress(){
File file = new File(filePath);
try {
Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath());
if(flagCamera==1) {
flagCamera=0;
compressedFile = new File(Environment.getExternalStorageDirectory().toString() + "/compressed" + file.getName());
FileOutputStream out = new FileOutputStream(compressedFile);
bitmap.compress(Bitmap.CompressFormat.JPEG,70,out);
out.flush();
out.close();
}else{
return file;
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return compressedFile;
}
public void postFeed(String commentString) {
RequestQueue mqueue = Volley.newRequestQueue(getActivity());
Map<String, String> params = new HashMap<String, String>();
params.put("access_token", SettingsHelper.getInstance(getActivity()).getPreference("auth_token"));
params.put("text", commentString);
params.put("user_id", SettingsHelper.getInstance(getActivity()).getPreference("id"));
params.put("privacy", Integer.toString(1));
TSUServerRequest.postFeed(getActivity(), mqueue, params, compress(), new Response.Listener<String>() {
#Override
public void onResponse(String s) {
Log.d("a", "bscljk");
filePath = "";
fileUri = null;
//Toast.makeText(getActivity(),"Success",Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
volleyError.printStackTrace();
}
});
}

Related

How can i upload a file to Kloudless from my android?

I wanted to upload a file from my android internal storage to Any cloud storage(ex.google drive,One drive etc)since kloudless provides an api to upload file to any cloud storage using accesstoken I wanted to use the same api for uploading the file (https://api.kloudless.com/v1/accounts/accountid+/storage/files/).
I tried it through postman I am able to upload the file
Now I tried through android volley I am able to create the file in the cloud but there is no data inside it. Here is my code
public class MainActivity extends AppCompatActivity {
Button b;
TextView TV;
File myFile;
String responseString;
String path;
public String BASE_URL = "https://api.kloudless.com";
private static final int FILE_SELECT_CODE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TV = findViewById(R.id.textView);
b = findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showFileChooser();
}
});
}
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == FILE_SELECT_CODE) {
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d("TAG", "File Uri: " + uri.toString());
// Get the path
String path = null;
try {
path = FileUtils.getPath(this, uri);
} catch (URISyntaxException e) {
e.printStackTrace();
}
Log.d("TAG", "File Path: " + path);
try {
data();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void data() throws FileNotFoundException, UnsupportedEncodingException {
final String url = BASE_URL + "/v1/accounts/" + "accountid" + "/storage/files/";
final RequestQueue queue = Volley.newRequestQueue(this);
HashMap<String, Object> params = new HashMap<String, Object>();
params.put( "file","somedata");
JSONObject Body=new JSONObject(params);
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url,Body, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// response
Log.d("Response", response.toString());
}
},
new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer Bearerkey");
params.put("Content-Type", "form-data");
params.put("X-Kloudless-Metadata", "{\"parent_id\":\"root\",\"name\":\"testdone.txt\"}");
// params.put("Content-Length", Space);
return params;
}
};
queue.add(request);
}
Please help me how to send the file in body of my request
I work at Kloudless and while I am not very familiar with the Android Volley, the issue here appears to be that you are setting a JSON body with the incorrect content type. In order to replicate the Postman request, you would need to use a multipart file upload instead, as described here: How to upload file using Volley library in android? The file would need to be added to a field called file, e.g entity.addPart("file", new FileBody(new File("....")));
In order for there to be more efficient handling on the server side (for larger files), the request performed should instead include the binary file contents in the request body and have the header Content-Type: application/octet-stream. Based on some cursory searching, it seems like the Volley library doesn't make that very easy so it might be best to try a different library.
Finally found the simple solution to upload a file to api
RequestQueue queue = Volley.newRequestQueue(this);
String url = BASE_URL + "/v1/accounts/" + "353284419" + "/storage/files/";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
// response
Log.d("Response", response);
}
},
new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer ix7wW4CFJsHxhttg42qsO6HNNRPh06");
params.put("Content-Type", "application/octet-stream");
params.put("X-Kloudless-Metadata", "{\"parent_id\":\"root\",\"name\":\"testing uplodes.pdf\"}");
// params.put("Content-Length", Space);
return params;
}
#Override
public byte[] getBody() throws com.android.volley.AuthFailureError {
File f=new File(path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] bytesArray = new byte[(int)f.length()];
try {
fis.read(bytesArray);
} catch (IOException e) {
e.printStackTrace();
}
return bytesArray;
};
};
postRequest.setRetryPolicy(new DefaultRetryPolicy(
40000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(postRequest);
}
just convert the file into binary array and send it in the body

Volley post request not sending data properly

I'm trying to send a base64 encoded string to a server over volley but its not sending properly. When i use httpbin this is the response
"args": {},
I/System.out: "data": "",
I/System.out: "files": {},
I/System.out: "form": { "/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAAqACAAQAAAABAAACiaADAAQAAAABAAAARQAAAAD/4QkhaHR0cDovL25zLmFkb2JlLmN...(image base64)
I/System.out: },
where the image data is in the form. However i need it in data.
public static String rawOutput = "dadsdas";
private Button buttonChoose;
private Button buttonUpload;
public String image;
private ImageView imageView;
private Button postText;
private EditText editTextName;
private Bitmap bitmap;
private int PICK_IMAGE_REQUEST = 1;
private String UPLOAD_URL ="https://httpbin.org/post";
private String KEY_IMAGE = "Content-Type";
private String KEY_NAME = "name";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_image);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
postText = (Button) findViewById(R.id.postText);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 50, baos);
byte[] imageBytes = baos.toByteArray();
System.out.println(imageBytes);
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage() throws JSONException {
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
// JSONObject jsonBody = new JSONObject();
// jsonBody.put(getStringImage(bitmap), "");
//final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
loading.dismiss();
System.out.println(s);
Toast.makeText(PostImage.this, s , Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
loading.dismiss();
String json = null;
NetworkResponse response = volleyError.networkResponse;
if(response != null && response.data != null){
switch(response.statusCode){
case 400:
json = new String(response.data);
if(json != null) System.out.println(json);
System.out.println(json.getClass().getSimpleName());
break;
}
//Additional cases
}
Toast.makeText(PostImage.this, volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
}){
// #Override
// public String getBodyContentType() {
// return "text/plain; charset=utf-8";
// }
// #Override
// public byte[] getBody() {
// byte[] body = new byte[0];
// try {
// body = ("/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAAqACAAQAAAABAAACiaADAAQAAAABAAAARQAAAAD/4QkhaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJYTVAgQ29yZSA1LjQuMCI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVz.......(image data here)");
//
//} catch (UnsupportedEncodingException exception) {
// Log.e("ERROR", "exception", exception);
// return null and don't pass any POST string if you encounter encoding error
//return null;
//}
return httpPostBody.getBytes();
}
// #Override
// public String getBody() throws AuthFailureError {
// image = getStringImage(bitmap);
// System.out.printf(image);
// String params= "";
// params= image;
// return params;
//
// }
// #Override
// protected Map<String, String> getParams() throws AuthFailureError {
// image = getStringImage(bitmap);
// System.out.printf(image);
// Map<String,String> params = new Hashtable<String, String>();
// params.put("", image);
// return params;
// }
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
System.out.println(stringRequest);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onClick(View v) {
if(v == buttonChoose){
showFileChooser();
}
if(v == buttonUpload){
try {
uploadImage();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public void postText(View v) {
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://api.getquesto.com:8080/upload";
JSONObject jsonBody = new JSONObject();
jsonBody.put("Text:", "A leaf is an organ of a vascular plant and is the principal lateral appendage of the stem.[1] The leaves and stem together form the shoot.[2] Leaves are collectively referred to as foliage, as in \"autumn foliage.\"[3][4]\n" +
"\n" +
"\n" +
"Diagram of a simple leaf.\n" +
"Apex Midvein (Primary vein) Secondary vein. Lamina. Leaf margin Petiole Bud Stem\n" +
"Although leaves can be seen in many different textures and sizes, typically a leaf is a thin, dorsiventrally flattened organ, borne above ground and specialized for photosynthesis. In most leaves, the primary photosynthetic tissue, the (palisade mesophyll), is located on the upper side of the blade or lamina of the leaf[1] but in some species, including the mature foliage of Eucalyptus,[5] palisade mesophyll is present on both sides and the leaves are said to be isobilateral. Most leaves have distinctive upper (adaxial) and lower (abaxial) surfaces that differ in colour, hairiness, the number of stomata (pores that intake and output gases), epicuticular wax amount and structure and other features.\n" +
"\n" +
"Broad, flat leaves with complex venation are known as megaphylls and the species that bear them, the majority, as broad-leaved or megaphyllous plants. In others, such as the clubmosses, with different evolutionary origins, the leaves are simple, with only a single vein and are known as microphylls.[6]\n" +
"\n" +
"Some leaves, such as bulb scales are not above ground, and in many aquatic species the leaves are submerged in water. Succulent plants often have thick juicy leaves, but some leaves are without major photosynthetic function and may be dead at maturity, as in some cataphylls, and spines). Furthermore, several kinds of leaf-like structures found in vascular plants are not totally homologous with them. Examples include flattened plant stems called phylloclades and cladodes, and flattened leaf stems called phyllodes which differ from leaves both in their structure and origin.[4][7] Many structures of non-vascular plants, such as the phyllids of mosses and liverworts and even of some foliose lichens, which are not plants at all (in the sense of being members of the kingdom Plantae), look and function much like leaves.");
final String mRequestBody = jsonBody.toString();
String json = null;
StringRequest stringRequest = new StringRequest(POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
Toast.makeText(PostImage.this, response , Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type","text/plain");
return params;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
}`
does anyone know how to make it send through data?

Multipart request using volley returning null as response

Hi I am relatively new to android, I have used multipart request to upload an image to server using volley. The image is being uploaded correctly but I am getting the response as null. I checked on postman, I am strangely getting the correct response there.
MultipartRequest.java
public class MultipartRequest extends Request<JSONObject> {
private static final String FILE_PART_NAME = "user[avatar]";
private long cacheTimeToLive = 0;
private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private final Response.Listener<JSONObject> mListener;
private final File mImageFile;
protected Map<String, String> headers;
public MultipartRequest(String url, File imageFile, Listener<JSONObject> listener, ErrorListener errorListener){
super(Method.PUT, url,errorListener);
mListener = listener;
mImageFile = imageFile;
buildMultipartEntity();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
headers.put("Accept", "application/json");
return headers;
}
private void buildMultipartEntity(){
mBuilder.addBinaryBody(FILE_PART_NAME, mImageFile, ContentType.create("image/jpeg"), mImageFile.getName());
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
}
#Override
public String getBodyContentType(){
String contentTypeHeader = mBuilder.build().getContentType().getValue();
return contentTypeHeader;
}
#Override
public byte[] getBody() throws AuthFailureError{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mBuilder.build().writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
}
return bos.toByteArray();
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
JSONObject result = null;
return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
}
#Override
protected void deliverResponse(JSONObject response) {
mListener.onResponse(response);
}
}
uploadImage method :-
private void uploadImage(final Bitmap bitmap){
String name = "DP_"+ userName +".jpeg";
try {
file=bitmapToFile(name,bitmap);
} catch (IOException e) {
e.printStackTrace();
}
MultipartRequest jsonRequest = new MultipartRequest( UPLOAD_URL,
file,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG,response.toString());
try {
// parseUserPhotoResponse(response);
Picasso.with(getApplicationContext())
.load(destination)
.placeholder(R.mipmap.placeholder)
.resize(avatarSize, avatarSize)
.centerCrop()
.transform(new CircleTransformation())
.into(ivUserProfilePhoto);
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Error: " + volleyError.getMessage());
if(volleyError!=null)
{
try {
NetworkResponse networkResponse = volleyError.networkResponse;
if (networkResponse != null) {
String responseBody = new String(volleyError.networkResponse.data, "utf-8");
JSONObject jsonObject = new JSONObject(responseBody);
Log.d(TAG, "Response body" + responseBody.toString());
Log.d(TAG, jsonObject.toString());
if (jsonObject.getBoolean("error") == false) {
} else {
Toast.makeText(getApplicationContext(), "" + jsonObject.getString("message"), Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
//Handle a malformed json response
} catch (UnsupportedEncodingException error) {
}
}
}
})
;
//Creating a Request Queue
jsonRequest.setShouldCache(false);
MyApplication.getInstance().addToRequestQueue(jsonRequest, "UPLOAD_IMAGE");
}

Open Image and make it a File in Android and send it in a Json

Ok so what I am trying to do is to open an image, set it in an imageview and make it a file in order to send it in a multipartform request using volley, right now I am using PostMan to make Http Requests to my server (string and file) and it is working properly but I can not implement it in android what I have so far is this
public void onClick(View v) {
if(v == banner){
Intent intent = new Intent();
//Verified the android version
if(Build.VERSION.SDK_INT < 19){
intent.setAction(Intent.ACTION_GET_CONTENT);
} else{
//KitKat 4.4 o superior
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
}
intent.setType("image/*");
startActivityForResult(intent, request_code);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK && requestCode == request_code) {
uri = data.getData();
banner.setImageURI(uri);
//TAG for store the Uri to the selected file
banner.setTag(uri);
path = uri.getPath();
fileImage = new File (path);
Toast.makeText(this,path,Toast.LENGTH_LONG).show();}
Where banner is my imageview and fileImage is my file
MultipartRequest myRequest = new MultipartRequest(
"MY_URL",
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("error");
}
},
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.e(response);
}
},
fileImage,
params
);
I am using this class that was answered in another question
public class MultipartRequest extends Request<String> {
//private MultipartEntity entity = new MultipartEntity();
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
HttpEntity httpentity;
private static final String FILE_PART_NAME = "banner";
private final Response.Listener<String> mListener;
private final File mFilePart;
private final Map<String, String> mStringPart;
public MultipartRequest(String url, Response.ErrorListener errorListener,
Response.Listener<String> listener,
File file,
Map<String, String> mStringPart) {
super(Method.POST, url, errorListener);
mListener = listener;
mFilePart = file;
this.mStringPart = mStringPart;
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
buildMultipartEntity();
}
public void addStringBody(String param, String value) {
mStringPart.put(param, value);
}
private void buildMultipartEntity() {
entity.addPart(FILE_PART_NAME, new FileBody(mFilePart));
for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
entity.addTextBody(entry.getKey(), entry.getValue());
}
}
#Override
public String getBodyContentType() {
return httpentity.getContentType().getValue();
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
httpentity = entity.build();
httpentity.writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
return Response.success("Uploaded", getCacheEntry());
}
#Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
}
But it return me the error "IOException writing to ByteArrayOutputStream"
If your goal is just saving the image to file, take a look at this post, you need to turn the image received as a bitmap first and then just follow what's written in that post

How to do upload image with Volley library?

I have an image and I want to upload this image to my web service using Volley library, the problem is I'm looking for a how to do it but still haven't found.
I found this, but doesn't work to me: http://develop-for-android.blogspot.com.br/2014/01/using-volley-in-your-application.html
How can I do this ?
I'm trying this.
#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) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
fotoPerfil = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
UploadoImageToServer upload = new UploadoImageToServer();
ApplicationController app = new UsuarioDAO().insert(usuario, upload.upload(fotoPerfil, em[0]), new UsuarioAdapter(){
#Override
public void usuarioIsAdded(Boolean result){
Log.i("Adicionou: ", result + "");
progress.dismiss();
}
});
CustomVolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(app);
public class UploadoImageToServer {
public String upload(String image,String nomeImagem){
Bitmap bitmap = BitmapFactory.decodeFile(image);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
return image_str;
}
}
/** add an user and upload your foto(image) */
public ApplicationController insert(Usuario u, String uploadFile, final UsuarioAdapter listener) {
boolean insert = false;
HashMap<String, String> params = new HashMap<String, String>();
params.put("nome", u.getNome());
params.put("email", u.getEmail());
params.put("senha", u.getSenha());
params.put("tipo", "usuarios");
params.put("acao", "add");
params.put("device_tipo", "android");
params.put("device", AndroidReturnId.getAndroidId());
params.put("uploadedfile", uploadFile);
Log.i("URL: ", urlPost.toString());
ApplicationController apc = new ApplicationController(Method.POST, urlPost.toString(), params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject obj) {
try {
if(obj.getString("cod").equals("999")){
listener.usuarioIsAdded(true);
}else{
listener.usuarioIsAdded(false);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
Log.e("ERROR METHOD:", "insert in UsuarioDAO: " + arg0.getLocalizedMessage());
}
});
return apc;
}
i am not much familier with volley, but give a try to the following code
//JSON Request
public MySampleImageUpload() {
JSONRequestResponse mResponse = new
JSONRequestResponse(mContext);
Bundle parms = new Bundle();
parms.putString("key_meail", "rojesh#demo.com");
parms.setFile("key_url", image_path);
mResponse.getResponse("sample_upload_data_url", REQUEST_CODE, this,
parms);
}
// In SetFile & getResponse code
package com.fartogram.utils;
import java.io.File;
import org.json.JSONObject;
import android.content.Context;
import android.os.Bundle;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.examples.toolbox.MultipartRequest;
import com.android.volley.examples.toolbox.MyVolley;
import com.android.volley.toolbox.JsonObjectRequest;
public class JSONRequestResponse {
public JSONRequestResponse(Context cntx) {
mContext = cntx;
}
private final Context mContext;
private int reqCode;
private IParseListener listner;
private boolean isFile = false;
private String file_path = "", key = "";
public void getResponse(String url, final int requestCode,
IParseListener mParseListener) {
getResponse(url, requestCode, mParseListener, null);
}
public void getResponse(String url, final int requestCode,
IParseListener mParseListener, Bundle params) {
this.listner = mParseListener;
this.reqCode = requestCode;
Response.Listener<JSONObject> sListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (listner != null) {
listner.SuccessResponse(response, reqCode);
}
}
};
Response.ErrorListener eListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (listner != null) {
listner.ErrorResponse(error, reqCode);
}
}
};
if (!isFile) {
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
Request.Method.GET, url, null, sListener,
eListener);
MyVolley.getRequestQueue().add(jsObjRequest);
} else {
if (file_path != null) {
File mFile = new File(file_path);
MultipartRequest multipartRequest =
new MultipartRequest(url,eListener, sListener, key, mFile, params);
MyVolley.getRequestQueue().add(multipartRequest);
}
}
}
public boolean isFile() {
return isFile;
}
public void setFile(String param, String path) {
if (path != null && param != null) {
key = param;
file_path = path;
this.isFile = true;
}
}
}
If it works for you mark it as right :)
You have to extend Request and use MultipartEntityBuilder if you wanna upload your image as a file.
public class ImageUploadWithVolley<T> extends Request<T> {
private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private final Response.Listener<T> mListener;
private final File yourImageFile;
protected Map<String, String> headers;
public ImageUploadWithVolley(String url, ErrorListener errorListener, Listener<T> listener, File imageFile) {
super(Method.POST, url, errorListener);
mListener = listener;
yourImageFile = imageFile;
addImageEntity();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
headers.put("Accept", "application/json");
return headers;
}
private void addImageEntity() {
mBuilder.addBinaryBody("give your image name", yourImageFile, ContentType.create("image/jpeg"), yourImageFile.getName());
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
}
#Override
public String getBodyContentType() {
String content = mBuilder.build().getContentType().getValue();
return content;
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mBuilder.build().writeTo(bos);
} catch (IOException e){
VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
}
return bos.toByteArray();
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response){
T result = null;
return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
}
#Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
}

Categories

Resources