How to upload Image on server using Volley?
Asked Answered
C

2

8

I'm trying to post my data using Volley but my i'm not able to upload my image on server. Always getting error like unexpected response code 500 for http:\\www.mybaseurl.com/upload.php. Following is my code by which i'm trying to upload

 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, s , 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, 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>()
            params.put("empsno", "81");
            params.put("storesno", "165");
            params.put("lrSno", "1808");
            params.put("recQty", "0");
            params.put("recVol", "0");
            params.put("recWgt", "0");
            params.put("damageQty", "0");
            params.put("looseQty", "0");
            params.put("deliveryDate", "2016-09-24");
            params.put("deliveryTime", "10:15");
            params.put("uploadFile", image);
            params.put("remarks", "mytestingrem");
            params.put("receivedBy", "amankumar");
            params.put("ipAddress", "12.65.65.32");

            //returning parameters
            return params;
        }
    };

    //Creating a Request Queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //Adding request to the queue
    requestQueue.add(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){
        uploadImage();
    }
}

Please help me , how to upload the file with these parameter. I'm new in volley. I simply copy paste this code from https://www.simplifiedcoding.net/android-volley-tutorial-to-upload-image-to-server . Even i don't know whether i'm using correctly or not. Thanks in advance

Convenance answered 26/9, 2016 at 13:3 Comment(7)
check it<techstricks.com/multipart-request-using-android-volley>.Latricelatricia
can U share your php code?Telophase
@Telophase php code i don't know. I know only the arguments and using rest (chrome extensiong) how to send data to serverConvenance
Best tutorial ever Upload Image On Server Using Volley Checkout the above link.Rapparee
@NessTyagi thanks bro... let me check this way also. I tried with retrofit but not get successConvenance
@NessTyagi same link I tried , and this code is followed by the same link. I also provided this link above in questionConvenance
You can check out this tutorial which uses Volley Multipart Request to upload image to server. simplifiedcoding.net/upload-image-to-serverSaidel
T
7

You should have to understand the concept to use of volley library and image uploads. Here are some other useful links for image upload and use of volley library.

volley library

Image upload using multipart

Note: I have also tested your tutorial.code are ok. Please check your image path properly. If possible then use their php code on any hosted web server. and check their json response and cross check your parameter which you have passed with server script's parameters..

Telophase answered 27/9, 2016 at 5:18 Comment(7)
if directly i'm inserting my code of image getting this error BasicNetwork.performRequest: Unexpected response code 500 for "example.com/upload directly means pastebin.com/N3iegMU8Convenance
Please be specific . I m not hetting whrere U insert code.Telophase
It;s so simple and excellent tutorial .You must have some knowledge of basic php concept(Basic query with database).I m again say that U are missing ur image path.Telophase
but I'm using imageView , where i'm getting the image successfullyConvenance
I followed the same tutorial and copy all from there , and simply changed my parameterConvenance
my log : net.simplifiedcoding.volleyupload E/Volley: [19262] BasicNetwork.performRequest: Unexpected response code 500 for 267.2.2.1/upload.phpConvenance
Link is not working anymoreSubstation
S
12

You can try this method ,which actually worked for my project.First you have to pick the image from gallery then it must be converted to string and sent via volley to server

// initialize
   private int PICK_IMAGE_REQUEST = 1;

    //set click listener 
         Upload.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //method to upload the image
                         showFileChooser();
       
                    }
                });
        

Method to open the gallery and to pick the image

                 private void showFileChooser() {
                     Intent pickImageIntent = new Intent(Intent.ACTION_PICK,
                 android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                pickImageIntent.setType("image/*");
                                pickImageIntent.putExtra("aspectX", 1);
                                pickImageIntent.putExtra("aspectY", 1);
                                pickImageIntent.putExtra("scale", true);
                                pickImageIntent.putExtra("outputFormat",
                                Bitmap.CompressFormat.JPEG.toString());
                                startActivityForResult(pickImageIntent, PICK_IMAGE_REQUEST); 
                         }
              

Add this method.Here the image is actually getting sent to server.

  @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 {
                                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                                Bitmap lastBitmap = null;
                                lastBitmap = bitmap;
                               //encoding image to string  
                                String image = getStringImage(lastBitmap);
                                Log.d("image",image);
                                //passing the image to volley
                                SendImage(image);
                         
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
        
       

 

Method to encode the image as string

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



    

uploading using volley

 private void SendImage( final String image) {
            final StringRequest stringRequest = new StringRequest(Request.Method.POST, "URL",
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Log.d("uploade",response);
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                               
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
    
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(Edit_Profile.this, "No internet connection", Toast.LENGTH_LONG).show();
                           
                        }
                    }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
    
                    Map<String, String> params = new Hashtable<String, String>();
                  
                    params.put("image", image);
                    return params;
                }
            };
            {
                int socketTimeout = 30000;
                RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
                stringRequest.setRetryPolicy(policy);
                RequestQueue requestQueue = Volley.newRequestQueue(this);
                requestQueue.add(stringRequest);
            }
        }
Saidel answered 9/8, 2017 at 18:18 Comment(1)
You should also mention that base64 will inflate the image data by 30% or so.Bailiwick
T
7

You should have to understand the concept to use of volley library and image uploads. Here are some other useful links for image upload and use of volley library.

volley library

Image upload using multipart

Note: I have also tested your tutorial.code are ok. Please check your image path properly. If possible then use their php code on any hosted web server. and check their json response and cross check your parameter which you have passed with server script's parameters..

Telophase answered 27/9, 2016 at 5:18 Comment(7)
if directly i'm inserting my code of image getting this error BasicNetwork.performRequest: Unexpected response code 500 for "example.com/upload directly means pastebin.com/N3iegMU8Convenance
Please be specific . I m not hetting whrere U insert code.Telophase
It;s so simple and excellent tutorial .You must have some knowledge of basic php concept(Basic query with database).I m again say that U are missing ur image path.Telophase
but I'm using imageView , where i'm getting the image successfullyConvenance
I followed the same tutorial and copy all from there , and simply changed my parameterConvenance
my log : net.simplifiedcoding.volleyupload E/Volley: [19262] BasicNetwork.performRequest: Unexpected response code 500 for 267.2.2.1/upload.phpConvenance
Link is not working anymoreSubstation

© 2022 - 2024 — McMap. All rights reserved.