Well this might sound a question that has been asked few often times but I could not come with a solution for the same.I want to upload image to server C#, i got codes for how to send image but don't know exactly how to use it. Please correct my code if there is something wrong and any idea about server side code for the same correction.
ProgressDialog progressDialog = new ProgressDialog(AddPropertyThird.this);
progressDialog.setMessage("Uploading, please wait...");
progressDialog.show();
//converting image to base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
final String imageString = Base64.encodeToString(imageBytes,Base64.DEFAULT);
//sending image to server
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(AddPropertyThird.this, "Some error occurred -> " + volleyError, Toast.LENGTH_LONG).show();
}
}) {
//adding parameters to send
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("imageFile", imageString);
return parameters;
}
};
RequestQueue rQueue = Volley.newRequestQueue(AddPropertyThird.this);
rQueue.add(request);
}
});
}
Logcat error
[879] BasicNetwork.performRequest: Unexpected response code 500
02-09 12:33:24.106 2 E/volleyerror: com.android.volley.ServerError
Related
Volley request is working just fine on the phone and emulator for the login activity but not for this one. See the error message and code below.
2021-02-20 22:23:25.695 29250-30267/com.bignerdranch.android.equipmentinspection E/Volley: [2336] BasicNetwork.performRequest: Unexpected response code 404 for https://sbmequipmentinspection.com/vehicleTable.php
2021-02-20 22:23:25.697 29250-29250/com.bignerdranch.android.equipmentinspection E/somethingWrong: com.android.volley.ClientError
private void uploadTOServer() {
String reg_url = "https://sbmequipmentinspection.com/vehicleTable.php";
final String loclaTime = android.text.format.DateFormat.format("yyyy-MM-dd hh:mm:ss a", mVehicle.getDate()).toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, reg_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getContext(),"Thank you for submitting vehicle inspection",Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("somethingWrong", error.toString());
Toast.makeText( getContext(),error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
String image = getStringImage(mPhotoFile);
Map<String,String> params = new HashMap<String, String>();
params.put("id", mVehicle.getID().toString());
params.put("user", SavePreference.getPrefUserName(getActivity()));
params.put("date",loclaTime);
params.put("vehicleNumber",mVehicle.getEquipmentNumber());
params.put("mileageNumber", mVehicle.getMilage());
params.put("question1" , mQuestionBank[0].getStatus());
params.put("question2", mQuestionBank[1].getStatus());
params.put("question3" , mQuestionBank[2].getStatus() );
params.put("question4", mQuestionBank[3].getStatus());
params.put("question5", mQuestionBank[4].getStatus());
params.put("question6", mQuestionBank[5].getStatus());
params.put("question7", mQuestionBank[6].getStatus());
params.put("question8", mQuestionBank[7].getStatus());
params.put("question9", mQuestionBank[8].getStatus());
params.put("question10", mQuestionBank[9].getStatus());
params.put("question11", mQuestionBank[10].getStatus());
params.put("question12", mQuestionBank[11].getStatus());
params.put("question13", mQuestionBank[12].getStatus());
params.put("addInfo", mVehicle.getExtraInfo());
params.put("status", mVehicle.getStatus());
params.put("image", image);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
stringRequest.setRetryPolicy(new DefaultRetryPolicy(0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(stringRequest);
}
private String getStringImage(File photoFile) {
Bitmap bitmap = PictureUtils.getScaledBitmap(photoFile.getPath(),getActivity());
ByteArrayOutputStream ba = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,ba);
byte[] imagebyte = ba.toByteArray();
String encode = Base64.encodeToString(imagebyte, Base64.DEFAULT);
return encode;
}```
This is what I would do. Firstly before the return I would create a string to check the JSON format, String mRequestBody = jsonObject.toString(); After that i would extract that JSON and put it into an Application known as Postman, https://www.postman.com/ and test if it still works there, let me know what you find?
I'm sending json data to server successfully.But problem in sending image.
I try the following thing:-
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage(){
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://toootapp.dreamsapps.com/ToootWebservice.asmx/SaveImage",
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
Log.e("img Response",s.toString().trim());
//Disimissing the progress dialog
loading.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("onErrorResponse=",getIntent().getStringExtra("path"));
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
// Toast.makeText(SaveImageOnServerActivity.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
// Log.e("Path=",getIntent().getStringExtra("path"));
Bitmap myBitmap = BitmapFactory.decodeFile(new File(getIntent().getStringExtra("path")).getAbsolutePath());
String image = getStringImage(myBitmap);
//Getting Image Name
String name = "Computer";//editTextName.getText().toString().trim();
//Creating parameters
Map<String,String> params = new Hashtable<String, String>();
//Adding parameters
params.put("base64Image", image);
params.put("Tags", "Computer");
//returning parameters
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
So I just want to check which json string is going to server.
Is there any way I can see what json string in the following form
{
"base64Image": "",
"Email": "abc#gmail.com",
"MobileNo": "1234567890",
"Website": "www.gameneeti.com",
"Industry": "Computer"
}
I send.
I want to print in log this string.
Thanks.
I've been looking for a way to upload a file using Volley API using the PUT method. All I've seen so far are through MultiPart POST method which aren't applicable to my case.
Assuming I can't change anything on the server side and I'm stuck with using PUT. How do I achieve this in volley?
Note that I only have the url where to upload the file and the file itself.
For uploading image file add the following functions to your StringRequest object.
Here outputFileUri is the Uri of the file which you want to upload.
#Override
public String getBodyContentType() {
return "image/jpeg";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream inputStream = mContext.getContentResolver().openInputStream(outputFileUri);
byte[] b = new byte[8192];
for (int readNum; (readNum = inputStream.read(b)) != -1; ) {
bos.write(b, 0, readNum);
}
inputStream.close();
return bos.toByteArray();
} catch (Exception e) {
Log.d(TAG, e.toString());
}
return null;
}
use the basic concept of PUT method
url = "your URL";
StringRequest putRequest = new StringRequest(Request.Method.PUT, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", response);
}
}){
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String> ();
params.put("name", "file_name");
return params;
}
}; RequestQueue queue = Volley.newRequestQueue(this);
queue.add(putRequest);
I have a simple task of uploading a base 64 encoded image to a server using Volley.
My server does not do anything. It just returns a 200 status code. But I always end up with this error even after the server returns 200. I tried some of the other solutions online but nothing seems to work.
private void uploadImage(){
obj = new JSONObject();
try {
obj.put("image", getStringImage(bitmap));
} catch (Exception e) {
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, UPLOAD_URL, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.e("Message from server", jsonObject.toString());
Toast.makeText(getApplication(), "Image Uploaded Successfully", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("Message from server", volleyError.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
return headers;
}
};
requestQueue.add(jsonObjectRequest);
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
I know this is late , but for me , the solution is to increase the http max post size in your server.for me I using spring boot with embedded tomcat server so the solution is to add the below line to your application.properties file:
server.tomcat.max-http-post-size=10000000
above I have set it to 10MB , another way of doing this is through java code as pointed by the answer in this link
Increase HTTP Post maxPostSize in Spring Boot
hope that helps you
I am developing an android application and I need to upload an Image to Following URL.
http://demo1.idevtechnolabs.com/RChatAPI/usrPhotos/
When I upload image to this URL the image should be stored in
http://demo1.idevtechnolabs.com/RChatAPI/usrPhotos/YourImage.jpg
and user can see it when he/she want from this url.
Please I have no idea what to do for this. please help me or send me any link for that.
Thanks in advance!
Follow the given step:
1)You've to convert your image into bitmap,
2)Convert the bitmap into Base64 String,
3)Send this string to server.
To represent this image:
1) Convert this Base64 into bitmap and set this bitmap into imageview.
Follow the given link
http://www.codeproject.com/Questions/464629/Pass-byte-as-parameter-to-JSON-service-from-Androi
Try this (using volley to upload image)
I am only writing snippets of upload method from android side and php file to receive the file(in the form of string)
ANDROID/JAVA code
// getStringImage method will be called inside uploadImage
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage(){
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Disimissing the progress dialog
loading.dismiss();
//Showing toast message of the response
Toast.makeText(MainActivity.this, "uploaded" , Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
Toast.makeText(MainActivity.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String image = getStringImage(bitmap);
//Getting Image Name
String name = editTextName.getText().toString().trim();
//Creating parameters
Map<String,String> params = new Hashtable<String, String>();
//Adding parameters
params.put(KEY_IMAGE, image);
params.put(KEY_NAME, "name");
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
PHP side img.php
<?php
$host="localhost"; //replace with database hostname
$username="root"; //replace with database username
$password=""; //replace with database password
$db_name="mydb"; //replace with database name
$con=mysql_connect($host,$username,$password);
$db=mysql_select_db($db_name);
$name = $_REQUEST['name']; //image name
$image = $_REQUEST['image']; //image in string format
$user=$_REQUEST['User_ID'];
$decodedImage = base64_decode($image);
$image_file=time().rand(1111,9999);
$name=$name.$image_file;
$base_path='/var/www/html/uploads/';
file_put_contents($base_path.$name.".jpg", $decodedImage);
mysql_query("INSERT into `image`(`img`,`User_ID`,`date`) values ('".$image_file.".jpg','$user',now() )");
echo mysql_insert_id();
?>
Its a late reply but I hope it helps someone else :)
If you have any trouble integrating the above code reply me .