0

I am trying for a simple image upload to local server


What I am trying to do :: I am trying to upload one image to server on click of button


  • I have referred this link
  • But i don't know how to implement the postData() function

Link i am trying to post the image::

http://10.0.2.2/Details/

with a name key for the image


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();


            }
        });
    }


    public void postData() {






    }

    /**
     * Method to post the image to the server.
     * U will have to change the url which will accept the image 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) {

            postData();

            return null;
        }

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

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

        }

    }

}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="32dp"
        android:clickable="false"
        android:src="@drawable/image" />

    <Button
        android:id="@+id/SUBMIT_BUTTON_ID"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="47dp"
        android:text="SUBMIT" />

</LinearLayout>

Any help on resolving this !



[EDIT- What i tried before]- I was not successful in getting the result

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
    {
        Drawable myDrawable = getResources().getDrawable(R.drawable.image);
        Bitmap bitmap = ((BitmapDrawable)myDrawable).getBitmap();
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost("http://10.0.2.2:7002/Details/");
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        try{
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.JPEG, 75, bos);
            byte[] data = bos.toByteArray();
            ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
            reqEntity.addPart("key", bab);
        }
        catch(Exception e){
            Log.v("MY-Error-Tag", "I got an error"+e);
            reqEntity.addPart("key", new StringBody(""));
        }
        postRequest.setEntity(reqEntity);       
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String sResponse;
        StringBuilder s = new StringBuilder();
        while ((sResponse = reader.readLine()) != null) {
            s = s.append(sResponse);
        }
    }

    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();

        }

    }

}

[FINAL-EDIT]

package com.example.datapostingproject;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

public class MainActivity extends Activity {

    Button submit;
    ProgressDialog pDialog;
    InputStream is;

    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() {
        Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
        byte [] ba = bao.toByteArray();
        String ba1=Base64.encodeToString(ba,Base64.DEFAULT);
        ArrayList<NameValuePair> nameValuePairs = new
                ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("key",ba1));
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new
                    HttpPost("http://10.0.2.2:7002/Details/");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
        }
    }
    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();

        }

    }

}

{stack stace on debugging } - in log

12-08 14:47:50.628: I/.......(433): TypeError: Cannot read property 'key' of undefined
12-08 14:47:50.628: I/.......(433):     at C:\ExpressPractice\imageUpload\app.js:17:32
12-08 14:47:50.628: I/.......(433):     at callbacks (C:\ExpressPractice\imageUpload\node_modules\express\lib\router\index.js:164:37)
12-08 14:47:50.628: I/.......(433):     at param (C:\ExpressPractice\imageUpload\node_modules\express\lib\router\index.js:138:11)
12-08 14:47:50.628: I/.......(433):     at pass (C:\ExpressPractice\imageUpload\node_modules\express\lib\router\index.js:145:5)
12-08 14:47:50.628: I/.......(433):     at Router._dispatch (C:\ExpressPractice\imageUpload\node_modules\express\lib\router\index.js:173:5)
12-08 14:47:50.628: I/.......(433):     at Object.router (C:\ExpressPractice\imageUpload\node_modules\express\lib\router\index.js:33:10)
12-08 14:47:50.628: I/.......(433):     at next (C:\ExpressPractice\imageUpload\node_modules\express\node_modules\connect\lib\proto.js:193:15)
12-08 14:47:50.628: I/.......(433):     at multipart (C:\ExpressPractice\imageUpload\node_modules\express\node_modules\connect\lib\middleware\multipart.js:86:27)
12-08 14:47:50.628: I/.......(433):     at C:\ExpressPractice\imageUpload\node_modules\express\node_modules\connect\lib\middleware\bodyParser.js:57:9
12-08 14:47:50.628: I/.......(433):     at C:\ExpressPractice\imageUpload\node_modules\express\node_modules\connect\lib\middleware\urlencoded.js:76:7
12-08 14:47:50.639: E/log_tag(433): Error in http connection java.lang.IllegalStateException: Content has been consumed

second-error trace after removing is = entity.getContent();

12-08 15:04:10.971: I/.......(461): TypeError: Cannot read property 'key' of undefined
12-08 15:04:10.971: I/.......(461):     at C:\ExpressPractice\imageUpload\app.js:17:32
12-08 15:04:10.971: I/.......(461):     at callbacks (C:\ExpressPractice\imageUpload\node_modules\express\lib\router\index.js:164:37)
12-08 15:04:10.971: I/.......(461):     at param (C:\ExpressPractice\imageUpload\node_modules\express\lib\router\index.js:138:11)
12-08 15:04:10.971: I/.......(461):     at pass (C:\ExpressPractice\imageUpload\node_modules\express\lib\router\index.js:145:5)
12-08 15:04:10.971: I/.......(461):     at Router._dispatch (C:\ExpressPractice\imageUpload\node_modules\express\lib\router\index.js:173:5)
12-08 15:04:10.971: I/.......(461):     at Object.router (C:\ExpressPractice\imageUpload\node_modules\express\lib\router\index.js:33:10)
12-08 15:04:10.971: I/.......(461):     at next (C:\ExpressPractice\imageUpload\node_modules\express\node_modules\connect\lib\proto.js:193:15)
12-08 15:04:10.971: I/.......(461):     at multipart (C:\ExpressPractice\imageUpload\node_modules\express\node_modules\connect\lib\middleware\multipart.js:86:27)
12-08 15:04:10.971: I/.......(461):     at C:\ExpressPractice\imageUpload\node_modules\express\node_modules\connect\lib\middleware\bodyParser.js:57:9
12-08 15:04:10.971: I/.......(461):     at C:\ExpressPractice\imageUpload\node_modules\express\node_modules\connect\lib\middleware\urlencoded.js:76:7

But from POSTMAN when i send image it works for 'key'

enter image description here

Still not successful in getting image posted !

Community
  • 1
  • 1
smriti3
  • 821
  • 2
  • 15
  • 34
  • the link you referred should work. its a http post request. What is the difficulty? – Raghunandan Dec 08 '13 at 07:38
  • @ Raghunandan ....I actually tried many times applying the solution.... never worked ..... i couldn't figure out the exact way to do posting for image( i was successful for only strings posting ) the so i posted this blank function ... it will really help you you could guide with your answer ... i have been trying this for weeks now :( – smriti3 Dec 08 '13 at 07:44
  • post your code for posting image. lets see what's wrong with it – Raghunandan Dec 08 '13 at 07:48
  • where is forest.jpg. you need the path of the image. – Raghunandan Dec 08 '13 at 08:03
  • @ Raghunandan ...... how can i give the path of the image here .... suppose my image is located in drawable-folder named as forest.jpg ..... please give me inputs on this... this will help – smriti3 Dec 08 '13 at 08:43

2 Answers2

1

Use the below an try

   public void postData() {
          Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
           ByteArrayOutputStream bao = new ByteArrayOutputStream();
           bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
           byte [] ba = bao.toByteArray();
           String ba1=Base64.encodeToString(ba,Base64.DEFAULT);
           ArrayList<NameValuePair> nameValuePairs = new
             ArrayList<NameValuePair>();
           nameValuePairs.add(new BasicNameValuePair("image",ba1));
           try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new
              HttpPost("http://10.0.2.2:7002/Details/");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
           }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
           }
    }

Edit:

Just for testing try uploading image from sdcard using file path

    try
    {
    String filepath= Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"Download"+File.separator+"ic_launcher.png";        
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httppost = new HttpPost("your url");
    File file = new File(filepath);
    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "image/jpeg");
    mpEntity.addPart("userfile", cbFile);
    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    String _response=EntityUtils.toString(entity);
    Log.i(".......",_response);
   }catch(Exception e){
    e.printStacktrace();
   }
Raghunandan
  • 129,147
  • 24
  • 216
  • 249
  • 1
    @smriti3 that is `InputStream is`. Look at `BasicNameValuePair("image",ba1))` – Raghunandan Dec 08 '13 at 09:01
  • @smriti3 you need to decode at the server side do you have code for that. and can't post images! what's wrong any exceptions errors??. what do you see in the log any response/ – Raghunandan Dec 08 '13 at 09:08
  • @smriti3 what do you see in the log using `HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); String _response=EntityUtils.toString(entity); Log.i(".......",_response);` – Raghunandan Dec 08 '13 at 09:13
  • @smriti3 remove this `is = entity.getContent();` use this HttpEntity `entity = response.getEntity(); String _response=EntityUtils.toString(entity); Log.i(".......",_response);` and check the response. in the log. that debug accordingly – Raghunandan Dec 08 '13 at 09:29
  • @ Raghunandan ........ please have a look at the error trace .... it still looks the same ... is this some issue for server ineed to resolve .... so so ...how could it accept data from POSTMAN an server works ? .... any ideas – smriti3 Dec 08 '13 at 09:38
  • 1
    @smriti3 i see nothing wrong on the android side. try uploading using a file from sdcard using file path . check the edit for testing. – Raghunandan Dec 08 '13 at 09:43
  • @smriti3 first converts image to byte array which is encoded. so you need the decoding part on the server side. So you need to something on the server. that's the exact reason i posted the edit fro testing purpose – Raghunandan Dec 08 '13 at 13:21
  • @smriti3 try this `mpEntity.addPart("photo", new ByteArrayBody(ba, filepath));` where `ba` is byte array. filepath is name the image. and second uses multipart if you see the edit. – Raghunandan Dec 08 '13 at 13:40
  • @ Raghunandan ....... Yes finally i did it, thank you ... successfully posted a single image ... now i will move on to multiple image posting .... Also have a look ... i have posted the complete solution as answers – smriti3 Dec 08 '13 at 13:58
0

Finally with the help of Raghunandan ...... from one of the answers .... found the solution


Ill post the complete answer so that .... this might be helpful to some-one 

MainActivity.java

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

public class MainActivity extends Activity {

    Button submit;
    ProgressDialog pDialog;
    InputStream is;

    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() {


        try
        {

        Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher); 

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost("http://10.0.2.2:7002/Details/");
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        try{
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmapOrg.compress(CompressFormat.JPEG, 75, bos);
            byte[] data = bos.toByteArray();
            ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
            reqEntity.addPart("key", bab);
        }
        catch(Exception e){
            //Log.v("Exception in Image", ""+e);
            reqEntity.addPart("picture", new StringBody(""));
        }
        postRequest.setEntity(reqEntity);       
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String sResponse;
        StringBuilder s = new StringBuilder();
        while ((sResponse = reader.readLine()) != null) {
            s = s.append(sResponse);
        }
    }catch(Exception e){
        e.getStackTrace();
    }

















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

        }

    }

}

ExpressJS code

app.js

var express=require('express');
var fs=require('fs');
var http=require('http');
var crypto=require('crypto');

var app=express();


app.set('port',process.env.PORT||7002); 

app.use('/Details',express.static(__dirname+'/public/images'));

//.use(express.cookieParser());

app.use(express.bodyParser());

app.post('/Details/',function(req,res,next){



        var file_name=req.files.key.originalFilename;
        console.log(file_name);

        crypto.randomBytes(8, function(ex, buf) {

                var array     = req.files.key.originalFilename.split('.');
                var type      = array[array.length - 1];
                var name      = buf.toString('hex') + '.' + type;

                fs.rename(req.files.key.path, './public/images/' + name, function(e) {


                        if (e) {
                                res.send(500, e.message);
                                } else 
                                {
                                    res.send("I got the message - This i confirm");
                                }

                });
        });
});

app.get('/Details/',function(req,res){
        res.send("Image displayed");
});

http.createServer(app).listen(app.get('port'),function(){
        console.log('Express server listening on port'+app.get('port'));

});

Point to keep in mind ::

  1. Make sure you send data as multipart from client(android)
  2. Then make sure u accept data on server side also as multipart
smriti3
  • 821
  • 2
  • 15
  • 34