2

Currently am using Volley to upload an Image to the server but the Image uploads with 0kb , without a Name even , The way i upload the image from android, i first turn my bitmap into a String then , the C# code on the server side turns the String back to the Bitmap, below is my java Code :

private String UPLOAD_URL  ="http://xxxxx:8092/PoliceApp/ImageUpload.aspx";

     private void onUploading() {

            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(CrimesReporting.this, s , Toast.LENGTH_LONG).show();
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            //Dismissing the progress dialog
                            loading.dismiss();
                            //Showing toast
                            Toast.makeText(CrimesReporting.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
                        }
                    }){
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    //Converting Bitmap to String
                    selectedFilePath = getStringImage(bitmap);
                  //  Uri selectedImageUri = data.getData();
                    //String video = getVideo(selectedImageUri);
                    File fileAttachment;
                    //Getting Image Name
                    String contact = contact_crimes.getText().toString().trim();
                    String PersonalContact = information_crimes_edt.getText().toString().trim();
                    String CrimesList = spinner.getSelectedItem().toString();
                    //Creating parameters
                    Map<String,String> params = new Hashtable<String, String>();
                    //Adding parameters
                    params.put("CrimeContact", contact);
                    params.put("CrimeInformation", PersonalContact);
                    params.put("CrimeDate", CrimesList);
                    params.put("photo",selectedFilePath);

                    //returning parameters
                    return params;
                }
            };
            //Creating a Request Queue
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            //Adding request to the queue
            requestQueue.add(stringRequest);
        }

And this is the code on the server side to Upload the Image to the server (Using Asp.net and C#) . But i have failed to place the Image and it's name in this method

SaveImage(ImagePic,ImageName);

Below is the code :

public partial class PoliceApp_ImageUploadaspx : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string ImagePic= "";
        string ImageName= "";
        SaveImage(ImagePic,ImageName);
    }
    public bool SaveImage(string ImgStr, string ImgName)
    {
        String path = HttpContext.Current.Server.MapPath("~/ImageStorage"); //Path
        //Check if directory exist
        if (!System.IO.Directory.Exists(path))
        {
            System.IO.Directory.CreateDirectory(path); //Create directory if it doesn't exist
        }
        string imageName = ImgName + ".jpg";
        //set the image path
        string imgPath = Path.Combine(path, imageName);
        byte[] imageBytes = Convert.FromBase64String(ImgStr);
        File.WriteAllBytes(imgPath, imageBytes);
        return true;
    }
}

2 Answers 2

2

You are only sending the path to the image in your request. This path won't be accessible from your server. I would also not recommend using a StringRequest for sending an image. Instead I would use something like this:

public class ImagePostRequest<T> extends Request<T> {
    private final byte[] body;

    public ImagePostRequest(Bitmap bitmap) {
        super(Request.Method.POST, UPLOAD_URL, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        });
        this.body = getBytesFromBitmap(bitmap);
    }

    // convert from bitmap to byte array
    public static byte[] getBytesFromBitmap(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
        return stream.toByteArray();
    }

    @Override
    public String getBodyContentType() {
        return "jpg/jpeg";
    }

    @Override
    public byte[] getBody() {
        return this.body;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Finally I got the answer myself. In the C# code I had to request for the parameters which were in the Android Java Volley Library:

params.put("ImagePic",selectedFilePath);
params.put("ImageName",timeStamp);

C# code requesting Android parameters as above:

        string ImagePic = Request["ImagePic"];
        string ImageName = Request["ImageName"];

Since the data comes from Android is parameterised, you have to request for it.

Note

The Android Java code is working fine, I just modified the C# code requesting for the image.

Below is the full C# code for saving an image to the server.

 protected void Page_Load(object sender, EventArgs e)
    {

        string ImagePic = Request.QueryString["ImagePic"];
        string ImageName = Request.QueryString["ImageName"];

        SaveImage(ImagePic,ImageName);
    }


    public bool SaveImage(string ImgStr, string ImgName)
    {
        String path = HttpContext.Current.Server.MapPath("~/ImageStorage"); //Path

        //Check if directory exist
        if (!System.IO.Directory.Exists(path))
        {
            System.IO.Directory.CreateDirectory(path); //Create directory if it doesn't exist
        }

        string imageName = ImgName + ".jpg";

        //set the image path
        string imgPath = Path.Combine(path, imageName);

        byte[] imageBytes = Convert.FromBase64String(ImgStr);

        File.WriteAllBytes(imgPath, imageBytes);

        return true;
    }

This may be of use for those who use Asp.net to make APIs instead of PHP and other languages.

2 Comments

This is not a very efficient way to transfer an image's data. Base64 encodes each set of three bytes into four bytes, plus some additional padding to ensure it is a multiple of 4. This means that the size of the base-64 representation of a string of size n is: ceil(n / 3) * 4 or roughly 30% extra size.
I want to add to Brian's comment. You can put your raw image data into the POST body and then in C# access that raw data with context.Request.InputStream. Another note is that many servers limit the length of the request URL. So if your image becomes too large you will be forced to switch to this method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.