Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Android How to upload image into the server using Volley library

    • 0
    • 0
    • 0
    • 7
    • 0
    • 0
    • 0
    • 26.2k
    Answer it
     I want to upload my captured images from camera to my 000webhost.com server using the volley library.
    
     I want where I am getting wrong and suggest me full code solution.
    
     I have tried to write the code, But its not working.
    

    I am getting error as follows:

     D/URL http://plantnow.net16.net/uploaded.php
     D/ERROR Error [com.android.volley.NoConnectionError: java.net.UnknownHostException:
    

    My PHP uploaded.php look like this. I want to s tore the images and imagepath in server.

       <?php
      if ($-SERVER['REQUEST-METHOD'] == 'POST') {
     $image = $&#95;POST['image'];
     require&#95;once('dbconnect.php');
     $sql ="SELECT id FROM images ORDER BY id ASC";
     $res = mysqli-query($con,$sql);
     $id = 0;
    
     while ($row = mysqli-fetch&#95;array($res)) {
         $id = $row['id'];
     }
    
     $path = "uploadedimages/$id.jpeg";
     $actualpath = "http://plantnow.net16.net/$path";
     $sql = "INSERT INTO images (image) VALUES ('$actualpath')";
    
    if (mysqli-query($con,$sql)) {
        file-put-contents($path,base64-decode($image));
        echo "Successfully Uploaded";
    }
    
    mysqli-close($con);
     } else {
    echo "Error";
    }
    ?>
    

    My main activity with volley code as follows:

          public class MainActivity extends Activity {
     ProgressDialog prgDialog;
     String encodedString;
     String fileName;
     private static int RESULT&#95;LOAD&#95;IMG = 1;
     private Button buttonUploadPhoto;
    private ImageView myimage;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity&#95;main);
    prgDialog = new ProgressDialog(this);
    // Set Cancelable as False
    prgDialog.setCancelable(false);
    
    buttonUploadPhoto = (Button) findViewById(R.id.uploadPhoto);
    myimage = (ImageView) findViewById(R.id.imgView);
    
    
    
    buttonUploadPhoto.setOnClickListener(new View.OnClickListener() {
    
        @Override
        public void onClick(View v) {
    
            uploadImage();
    
        }
       });
    
      }
    
     public void loadImagefromGallery(View view) {
    // Create intent to Open Image applications like Gallery, Google Photos
    Intent galleryIntent = new Intent(Intent.ACTION&#95;PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL&#95;CONTENT&#95;URI);
    // Start the Intent
    startActivityForResult(galleryIntent, RESULT&#95;LOAD&#95;IMG);
     }
    
        // When Image is selected from Gallery
         @Override
         protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          super.onActivityResult(requestCode, resultCode, data);
          if (requestCode == RESULT&#95;LOAD&#95;IMG && resultCode == RESULT&#95;OK && null != data) {
          Uri selectedImage = data.getData();
          String[] filePathColumn = { MediaStore.Images.Media.DATA };
          Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
          cursor.moveToFirst();
           int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
           String picturePath = cursor.getString(columnIndex);
          cursor.close();
    
          String fileNameSegments[] = picturePath.split("/");
          fileName = fileNameSegments[fileNameSegments.length - 1];
    
        Bitmap myImg = BitmapFactory.decodeFile(picturePath);
        myimage.setImageBitmap(myImg);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        // Must compress the Image to reduce image size to make upload easy
        myImg.compress(Bitmap.CompressFormat.PNG, 50, stream);
        byte[] byte&#95;arr = stream.toByteArray();
        // Encode Image to String
        encodedString = Base64.encodeToString(byte&#95;arr, 0);
    
        uploadImage();
       }
       }
    

    /** * API call for upload selected image from gallery to the server */ public void uploadImage() {

       RequestQueue rq = Volley.newRequestQueue(this);
       String url = "http:/plantnow.net16.net/uploaded.php";
       Log.d("URL", url);
           StringRequest stringRequest = new StringRequest(Request.Method.POST,
            url, new Response.Listener<String>() {
    
        @Override
        public void onResponse(String response) {
            try {
                Log.e("RESPONSE", response);
                JSONObject json = new JSONObject(response);
    
                Toast.makeText(getBaseContext(),
                        "The image is upload", Toast.LENGTH&#95;SHORT)
                        .show();
    
            } catch (JSONException e) {
                Log.d("JSON Exception", e.toString());
                Toast.makeText(getBaseContext(),
                        "Error while loadin data!",
                        Toast.LENGTH&#95;LONG).show();
            }
    
        }
    
        }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("ERROR", "Error [" + error + "]");
            Toast.makeText(getBaseContext(),
                    "Cannot connect to server", Toast.LENGTH&#95;LONG)
                    .show();
        }
         }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
    
            params.put("image", encodedString);
            params.put("filename", fileName);
    
            return params;
    
          }
    
       };
       rq.add(stringRequest);
    }
    
      @Override
      protected void onDestroy() {
     // TODO Auto-generated method stub
       super.onDestroy();
     // Dismiss the progress bar when application is closed
       if (prgDialog != null) {
         prgDialog.dismiss();
       }
       }
    

 7 Answer(s)

  • Hello Bharat,

    Please check line no 2 of your code in uploadImage() method,

    error 
    String url = "http:/plantnow.net16.net/uploaded.php"; 
    
    correction 
    String url = "http://plantnow.net16.net/uploaded.php"; 
    

    please find the attached working code that i tested with the url you provided on my server its working but in case of the server you are using i am getting the following response.

    Error

    <!-- Hosting24 Analytics Code -->
    <script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
    <!-- End Of Analytics Code -->
    

    that seems the part of php end that is not allowing to upload the image.

  • Hi Bharat,

    Please mark the answer as correct if you find it helped you. For your second query that is uploading image from camera its similar as gallery you need to change the request code and open camera then after just do the same thing, will update you with the code soon.

    Enjoy codeing :)

  • Look ,We have two methods for uploading images to server

    1. Using Multipart request.

    2. Sending the image String to server.

    In volley we can use both of them. But your case is second one.

    This is Volley's post request that you are using and it should work .

    Are you using proper internet permission in your manifest?

  • Devesh,

    My php is working fine. My question is How to upload images using volley. And I have already decoded image.

    How to store captured image and after uploading to server, it should show message "image uploaded"

  • Hello bharat , your code is converting the image into encoded string and Sending that String to server.

    You need to decode that String in PHP Script.

    <php>
    // $data is post image string 
    $data = base64&#95;decode($data);
    </php>
    

    Reference:

    http://php.net/manual/en/function.imagecreatefromstring.php

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: