smriti3
smriti3

Reputation: 871

sending a single image to the server from android

I am trying to post a single image to the server



What i have tried::

MainActivity.java

public class MainActivity extends Activity {

    Button submit;
    ProgressDialog pDialog;

    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        submit = (Button) findViewById(R.id.SUBMIT_BUTTON_ID);

        imageView = (ImageView) findViewById(R.id.imageView1);

        submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new MainTest().execute();


            }
        });
    }




    /**
     * Method to post the image to the server.
     * U will have to change the url which will accept the image data.
     */
    private void postImageData(){

        //Some random id. u can change this based on requirements
        String newurl = "?" + "key=" + new Random().nextLong();
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://54.218.73.244:7002/Details/"+newurl);

        //Convert the bitmap drawble to a bitmap and get the string after that to send to the server
        Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] bitmapdata = stream.toByteArray();
        String image_str = Base64.encodeToString(bitmapdata, Base64.DEFAULT);

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("imageData", image_str));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            Log.v("Response", response.toString());

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }

    }

    public class MainTest extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading..");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {

            postImageData();

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub

            super.onPostExecute(result);
            // data=jobj.toString();
            pDialog.dismiss();

        }

    }

}

How can i resolve this ?


[EDIT]

I checked whether the server is running correctly or not for accepting the images, but it looks running perfectly fine ! when checked with postman-tool for uploading images, so problem has to be the client part

MainActivity.java

public class MainActivity extends Activity {

    Button submit;
    ProgressDialog pDialog;

    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        submit = (Button) findViewById(R.id.SUBMIT_BUTTON_ID);

        imageView = (ImageView) findViewById(R.id.imageView1);

        submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new MainTest().execute();


            }
        });
    }



    /**
     * Method to post the image to the server.
     * U will have to change the url which will accept the image data.
     * @throws IOException 
     */
    public void postImageData() throws IOException
    {
         //Some random id. u can change this based on requirements
        String newurl = "?" + "key=" + new Random().nextLong();
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://54.218.73.244:7002/Details/"+newurl);

        //Convert the bitmap drawble to a bitmap and get the string after that to send to the server
        Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
        String dir = Environment.getExternalStorageDirectory().toString();
        OutputStream fos = null;

        File file = new File(dir,"temp.JPEG");
        fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);

        bos.flush();
        bos.close();

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        File mFile = new File(dir, "temp.JPEG");
        FileBody encFile = new FileBody(mFile,"image/jpeg");
        entity.addPart("images", encFile);
        //Another key/value parameter
        //entity.addPart("UserId", new StringBody(userId)); 

        httppost.setEntity(entity);

        HttpClient client = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(httppost);                

        String data = EntityUtils.toString(response.getEntity());
        System.out.println("response data:"+data);
    }

    public class MainTest extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading..");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {

            try {
                postImageData();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub

            super.onPostExecute(result);
            // data=jobj.toString();
            pDialog.dismiss();

        }

    }

}

Upvotes: 1

Views: 1394

Answers (2)

Amresh
Amresh

Reputation: 2108

You can try out this.

public class MainActivity extends Activity {
        Bitmap bm;
        String url_path = "http://yoururl.php?";

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            try {
                bm = BitmapFactory.decodeResource(getResources(), R.drawable.annag);

                // bm = BitmapFactory.decodeFile("/sdcard/DCIM/forest.png");
                executeMultipartPost();
            } catch (Exception e) {
                Log.e(e.getClass().getName(), e.getMessage());
            }
        }

        public void executeMultipartPost() throws Exception {

            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bm.compress(CompressFormat.JPEG, 75, bos);
                byte[] data = bos.toByteArray();
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost postRequest = new HttpPost(url_path);
                ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
                                MultipartEntity reqEntity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);

                reqEntity.addPart("store_name", new StringBody("amazon"));
                reqEntity.addPart("file", bab);
                postRequest.setEntity(reqEntity);

                HttpResponse response = httpClient.execute(postRequest);

                String my_response = convertStreamToString(response.getEntity()
                        .getContent());
                Toast.makeText(getApplicationContext(), my_response,
                        Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        public static String convertStreamToString(InputStream is) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();

            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return sb.toString();
        }

Upvotes: 0

Niranj Patel
Niranj Patel

Reputation: 33238

You have to use MultipartEntity for upload Image to Server

  public void postImageData()
    {
         //Some random id. u can change this based on requirements
        String newurl = "?" + "key=" + new Random().nextLong();
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://54.218.73.244:7002/Details/"+newurl);

        //Convert the bitmap drawble to a bitmap and get the string after that to send to the server
        Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
        String dir = Environment.getExternalStorageDirectory().toString();
        OutputStream fos = null;

        File file = new File(dir,"temp.JPEG");
        fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);

        bos.flush();
        bos.close();

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        File mFile = new File(dir, "temp.JPEG");
        FileBody encFile = new FileBody(mFile,"image/jpeg");
        entity.addPart("images", encFile);
        //Another key/value parameter
        //entity.addPart("UserId", new StringBody(userId)); 

        httppost.setEntity(entity);

        HttpClient client = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(httppost);                

        String data = EntityUtils.toString(response.getEntity());
        System.out.println("response data:"+data);
    }

Upvotes: 2

Related Questions