I'm facing a issue in uploading image more than 2 MB.
Kindly please help me with this problem. This error
java.net.SocketException:Broken pipe
Displayed in a Toast.
This is code for getting image in Base64 format and uploading on server.
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos=new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG,100, baos);
byte [] b=baos.toByteArray();
String encodedImage= null;
try{
System.gc();
encodedImage= Base64.encodeToString(b, Base64.DEFAULT);
}catch(Exception e){
e.printStackTrace();
}catch(OutOfMemoryError e){
baos=new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG,50, baos);
b=baos.toByteArray();
encodedImage=Base64.encodeToString(b, Base64.DEFAULT);
Log.e("EWN", "Out of memory error catched");
}
return encodedImage;
}
private void uploadImage(){
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(getActivity(), "Uploading...", "Please wait...", false, false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.UPLOADIMAGE_URL+"/user",
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
//Disimissing the progress dialog
loading.dismiss();
//Showing toast message of the response
System.out.println("Response :" + s);
JSONObject jsonObject = new JSONObject(s);
Preferences.setUserImageUrl(getActivity(), jsonObject.getString("image_name"));
// MainActivity mains = new MainActivity();
// Picasso.with(mains).load(finalImageUrl).placeholder(R.drawable.profile_image).into(mains.profile_image);
// mains.updateimage(jsonObject.getString("image_name"));
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(getActivity(), s , Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
if (volleyError.getMessage()==null){
Toast.makeText(getActivity(), "Image not uploaded Please check your internet ", Toast.LENGTH_SHORT).show();
}else {
//Showing toast
Toast.makeText(getActivity(), volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String image = getStringImage(bitmap);
//Creating parameters
Map<String,String> params = new Hashtable<String, String>();
//Adding parameters
params.put("image", image);
System.out.println("image : " + image);
params.put("id", Preferences.getUserId(getActivity()));
System.out.println("ID : "+Preferences.getUserId(getActivity()));
return checkParams(params);
}
//returning parameters
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request to the queue
requestQueue.add(stringRequest);
//AppController.getInstance().addToRequestQueue(stringRequest);
}
private Map<String, String> checkParams(Map<String, String> map) {
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next();
if (pairs.getValue() == null) {
map.put(pairs.getKey(), "image");
map.put(pairs.getKey(), "id");
}
}
return map;
}
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == getActivity().RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);
//Setting the Bitmap to ImageView
userImage.setImageBitmap(bitmap);
uploadImage();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It's my code..
Related
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
I have written the code for capturing the image from the camera and send to the server. But sometimes it works sometimes its not with the error volley timeout error. And almost all the cases when I am using JIO network which used IPv6 IP( I don't know what is affecting this) its not working.
I am capturing the image and convert into base64 and sending to the POST to the PHP server.
To start the camera :
btn_cam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
captureImage();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,CAMERA_REQUEST_CODE);
} catch (Exception e){
e.printStackTrace();
}
}
});
After capturing the image :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
}
}
Then sending the encoded string to the APACHE server :
btn_submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
_house_no = house_number.getText().toString();
_state = state.getText().toString();
_streetName = locality.getText().toString();
_city = city.getText().toString();
_postalCode = postcode.getText().toString();
_state = state.getText().toString();
_district = district.getText().toString();
_tahsil = "0";
final ProgressDialog loading = ProgressDialog.show(MainActivity.this, "", "Please wait...", false, false);
try {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
String URL = ServerLinks.SUBMIT;
JSONObject jObj = new JSONObject();
jObj.put("userID",userID);
jObj.put("house",_house_no);
jObj.put("street",_streetName);
jObj.put("city",_city);
jObj.put("post_code",_postalCode);
jObj.put("state",_state);
jObj.put("district",_district);
jObj.put("lat",lat);
jObj.put("long",longi);
jObj.put("image",encoded);
final String requestBody = jObj.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("FINAL_SUBMIT_RESPONSE", response.toString());
loading.dismiss();
try {
JSONObject object = new JSONObject(response);
int response_code = object.getInt("code");
String message = object.getString("Message");
if (response_code == 400) {
Snackbar.make(rootLinearLayout, message, Snackbar.LENGTH_SHORT).show();
house_number.setText("");
} else {
Snackbar.make(rootLinearLayout, message, Snackbar.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
VolleyLog.d("RESULT_ERROR", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Something Went Wrong!! Please submit it again", Toast.LENGTH_SHORT).show();
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("x-api-key", OAuth);
return params;
}
};
stringRequest.setShouldCache(false);
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}`
Can you please help me how should I increase the efficiency of my form with the image. Thank You in advance
Inside my code I have done this like that :
HttpClient httpclient;
httpclient = HttpClientSingalTon.getHttpClienttest();
HttpPost httpPostRequest = new HttpPost(URL);
// Try This
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(yourimagefile, "image/jpeg");
mpEntity.addPart("file", cbFile);
httpPostRequest.setEntity(mpEntity);
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CAPTURE_IMAGE && resultCode == RESULT_OK) {
bitmapFrontIC = (Bitmap) data.getExtras().get("data");
frontICImageView.setImageBitmap(bitmapFrontIC);
}else if(requestCode == REQUEST_CAPTURE_BACKIC && resultCode == RESULT_OK){
bitmapBackIC = (Bitmap) data.getExtras().get("data");
backICImageView.setImageBitmap(bitmapBackIC);
}
}
submitbuttonOnClick:
public void submitOnClick(View view){
Log.d("Submit clicked", "Submit Clicked");
if(icNumber.getText().toString().length() > 0 && bitmapFrontIC != null && bitmapBackIC != null){
uploadBitmap(bitmapFrontIC,bitmapBackIC);
}else{
Toast.makeText(getApplicationContext(), "Please fill up all the fields", Toast.LENGTH_SHORT).show();
}
}
GetFileDataFromDrawable:
public byte[] getFileDataFromDrawable(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
uploadBitMap:
private void uploadBitmap(final Bitmap bitmapFrontIC, final Bitmap bitmapBackIC) {
//our custom volley request
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, Constants.API_URL + "/users/upload-ic",
new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
loading.dismiss();
try {
JSONObject obj = new JSONObject(new String(response.data));
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
error.printStackTrace();
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null && networkResponse.data != null) {
String errorResponse = new String(networkResponse.data);
try {
JSONObject errorObject = new JSONObject(errorResponse);
if(errorObject.has("error")){
Toast.makeText(ICVerificationActivity.this, errorObject.getString("message"),
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
// Print Error!
Log.d("JSON ERROR", errorResponse);
}
}
}) {
/*
* If you want to add more parameters with the image
* you can do it here
* here we have only one parameter with the image
* which is tags
* */
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("icno", icNumber.getText().toString());
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "multipart/form-data");
headers.put("Authorization", "Bearer " + "abcd");
return headers;
}
/*
* Here we are passing image by renaming it with a unique name
* */
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
long imageName = System.currentTimeMillis();
params.put("icFront", new DataPart("FrontIC_" + imageName + ".png", getFileDataFromDrawable(bitmapFrontIC)));
params.put("icBack", new DataPart("BackIC_"+imageName + ".png", getFileDataFromDrawable(bitmapBackIC)));
return params;
}
};
//adding the request to volley
Volley.newRequestQueue(this).add(volleyMultipartRequest);
loading.show();
}
I am trying to call the POST request by inputting three items to the body:
a) text
b) camera_image1
c) camera_image2
I am able to display the captured image from camera in the imageview which means the bitmap is working. However, when I want to upload to the server, the server returns that the images are empty. Am I doing it wrongly?
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?
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();
}
});
}