Send byte[] from android volley to asp.net mvc - android

I am trying to upload an image from android to asp.net mvc webapp. I've the following code to upload image on android part -
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 String UPLOAD_URL ="UploadSignature?id=1";
private String KEY_IMAGE = "image";
private String KEY_NAME = "name";
private Bitmap bitmap;
private void uploadImage(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
String image = getStringImage(bitmap);
String name = "firstImage";
Map<String,String> params = new Hashtable<String, String>();
params.put(KEY_IMAGE, image);
params.put(KEY_NAME, name);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
In asp.net mvc controller-
[HttpPost]
public ActionResult UploadSignatureTwo(byte[] Data)
{
System.IO.File.WriteAllBytes( #"D:\test.jpg", Data);
}
But it says Data can not be null.
Any help?

Related

Volley doesnot connect with flask server

My java code is not connect with flask. It doesn't give any error or response. Program run infinitely.
When i try to connect it is not going on response or on error function. After completing function call it start running and never stop.
Java Code:
Button button;
RequestQueue rQueue;
String url ="http://127.0.0.1:5000/predict";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
rQueue = Volley.newRequestQueue(MainActivity.this);
}
public void predict(View view){
UploadTwoImages();
}
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;
}
public void UploadTwoImages() {
Bitmap icon = BitmapFactory.decodeResource(getResources(),R.drawable.logo);
final String imageOne = getStringImage(icon);
final ProgressDialog pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Registration is in Process Please wait...");
pDialog.show();
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
pDialog.dismiss();
Log.d("JSONResult", s);
try {
JSONObject jObject = new JSONObject(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}) {
//adding parameters to send
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("image", imageOne);
return parameters;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(
90000,
0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
request.setShouldCache(false);
rQueue.add(request);
}
Flask Server Code:
#app.route('/predict', methods=['GET', 'POST'])
def upload():
if request.method == "POST":
if request.files:
output={}
image = request.files["image"]
print(request.files)
basepath = os.path.dirname(__file__)
file_path = os.path.join(
basepath, 'uploads', secure_filename(image.filename))
print(image.filename)
image.save(file_path)
return str([1])
return "Error"
if __name__ == '__main__':
app.run(debug=True)
url = ipv4address:portNumber/apiName
In android manifest add following 2 lines and it works for me.
android:usesCleartextTraffic="true"
<uses-permission android:name="android.permission.INTERNET"/>

how to see json data send to server in volley in android

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.

Upload image to server c# android

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

Android Volley ECONNRESET

I try to use Volley library and upload image to server. This library should do this process in standalone mode, but have got following error message:
java.net.SocketException: sendto failed: ECONNRESET (Connection reset
by peer)
Is it maybe a server side misconfiguration?
I try to upload a jpeg image with this code:
private void uploadImage(){
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) {
loading.dismiss();
Toast.makeText(PhotoActivity.this, s , Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
loading.dismiss();
Toast.makeText(PhotoActivity.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
String image = getStringImage(bitmap);
String name = editTextName.getText().toString().trim();
Map<String,String> params = new Hashtable<String, String>();
params.put(KEY_IMAGE, image);
params.put(KEY_NAME, name);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
just to be sure, you need to change your uploadImage() into something like this:
private void uploadImage(){
final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
//here you use your custom multi-part-request as I suggested in the comment:
ImageUploadRequest imageUploadReq = new ImageUploadRequest(UPLOAD_URL,
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
loading.dismiss();
Toast.makeText(PhotoActivity.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
},
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
loading.dismiss();
Toast.makeText(PhotoActivity.this, s , Toast.LENGTH_LONG).show();
}
}, yourImageFile);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(imageUploadReq);
}
Where your ImageUploadRequest class is defined as demonstrated in the accepted answer here like this:
public class ImageUploadRequest<T> extends Request<T> {
private static final String FILE_PART_NAME = "file";
private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private final Response.Listener<T> mListener;
private final File mImageToUpload;
protected Map<String, String> headers;
public ImageUploadRequest(String uploadURL, ErrorListener errorListener, Listener<T> listener, File imageFileToUpload){
super(Method.POST, uploadURL, errorListener);
mListener = listener;
mImageToUpload = imageFileToUpload;
//call the helper method to build the multipart entity
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, mImageToUpload, ContentType.create("image/jpeg"), mImageToUpload.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<T> parseNetworkResponse(NetworkResponse response) {
T result = null;
return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
}
#Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
}
I have made some minor adaptations of Upload an image using Google Volley to your specific situation. I hope this helps you and that others may also find it useful.
I usually get this error when I don't use url encoded queries.
Take a look URL encoding in Android

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

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();
}
});
}

Categories

Resources