Lutaaya Huzaifah Idris
Lutaaya Huzaifah Idris

Reputation: 3990

Image Upload android Java + Asp.net (C#)

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

Upvotes: 2

Views: 551

Answers (2)

Lutaaya Huzaifah Idris
Lutaaya Huzaifah Idris

Reputation: 3990

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.

Upvotes: 0

Brian P. Hamachek
Brian P. Hamachek

Reputation: 935

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

Upvotes: 2

Related Questions