2

User can take 5-6 pictures in android side through camera. So, I used ACTION_IMAGE_CAPTURE. In the onActivityResult I do this to collect the bitmap of the image taken by the camera. Suppose for first taken pic and second taken pic as below.

if(requestCode == 1)
{
    bitMap1 = (Bitmap)extras.get("data");
    imageView1.setImageBitmap(bitMap1);
    globalvar = 2;
}
if(requestCode == 2)
{
    bitMap1 = (Bitmap)extras.get("data");
    imageView2.setImageBitmap(bitMap2);
    globalvar = 2;
}

To send these images to the php server, I do the following..

protected String doInBackground(Integer... args) {
            // Building Parameters


    ByteArrayOutputStream bao1 = new ByteArrayOutputStream();
    bitMap1.compress(Bitmap.CompressFormat.JPEG, 90, bao1);
    byte [] bytearray1 = bao1.toByteArray();
    String stringba1 = Base64.encode(bytearray1);


 ByteArrayOutputStream bao2 = new ByteArrayOutputStream();
    bitMap2.compress(Bitmap.CompressFormat.JPEG, 90, bao2);
    byte [] bytearray2 = bao2.toByteArray();
    String stringba2 = Base64.encode(bytearray2);


            String parameter1 = "tenant";
                String parameter2 = "price";

            List<NameValuePair> params = new ArrayList<NameValuePair>();

                params.add(new BasicNameValuePair("person",parameter1));
                params.add(new BasicNameValuePair("price",parameter2));
                params.add(new BasicNameValuePair("image1",stringba1));
                params.add(new BasicNameValuePair("image2",stringba2));

            JSONObject json = jParser.makeHttpRequest(requiredurl, "POST", params);


            Log.d("Details", json.toString());



                int success = json.getInt("connected");

                if (success == 1) {

                    //blah blah
                      }
        }

Here is the makeHttpRequest() method:

public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){

                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);

                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }       

       ................
       ....................... // Here the result is extracted and made it to json object
       .............................

        // return JSON 
        return jObj;  // returning the json object to the method that calls.

    }

Below is the php code snippet:

$name = $_POST[person];
$price = $_POST[price];
$binary1 = base64_decode($image2);
$binary2 = base64_decode($image2);

$file1 = tempnam($uploadPath, 'image2');
$fp1  = fopen($file1, 'wb');
fwrite($fp1, $binary1);
fclose($fp1);
.................
............................

However I am unable to store images in sever side folder. Even I have seen in some links saying that Base64 is not preferable way while uploading multiple images. Can someone please suggest me how to proceed? Have seen this and many other links, but can't get how to proceed in my requirement as I have to even send some data(like person name, price) along with that images. Any help on this is greatly appreciated.

NOTE: Even if someone can suggest me how to save that above temp file($file1) in the server folder, I would be very thankful.

Community
  • 1
  • 1
Korhan
  • 323
  • 2
  • 4
  • 20
  • use a standard HTTP post. base64 increases size of data by about 33%. your users would not be happy if your app blows through their data caps. – Marc B Jan 28 '13 at 16:56
  • Why dont u use multipartEntity?? – Payal Jan 28 '13 at 17:00
  • @MarcB I am using HttpPost only, right? It's there in my code. So, is it not standard? Please suggest me the solution to proceed. I have been struggling with this. – Korhan Jan 28 '13 at 17:01
  • well, you're not doing a standard multipart-type file upload. – Marc B Jan 28 '13 at 17:02
  • @Marc B Isn't multipart upload base64 encoded by default? – greenapps Jan 28 '13 at 19:45
  • @Korhan If you set $uploadPath to your server folder then the images will be put there. What's the problem? Didn't you forget $image2=$_POST['image2']; – greenapps Jan 28 '13 at 19:47
  • @greenapps No. I kept that too. But my problem is with base64 I guess. Can you suggest me another efficient way to do this? – Korhan Jan 29 '13 at 02:45
  • @Payal Is it possible to send even string data with multipartEntity? Moreover I have seen in some posts that large files couldn't be sent with that, is it true? – Korhan Jan 29 '13 at 02:58
  • @Korhan yeah, we can definately send strings through multipartEntity. for example : bin = new FileBody(tempImg, "image/jpg"); reqEntity.addPart("lpa", bin);// image reqEntity.addPart("count_lpa",new StringBody("1"));//String And what is the size of image you are trying to send?? I have sent images of around 5 Mb and this has worked fine for me. – Payal Jan 29 '13 at 08:24
  • @Payal Even my images are around 5Mb. Can you post a solution with your code? I would be very thankful. – Korhan Jan 29 '13 at 08:48
  • @Korhan see this link.It will definately help you. http://blog.tacticalnuclearstrike.com/2010/01/using-multipartentity-in-android-applications/ – Payal Feb 01 '13 at 06:10
  • @Payal Thank you so much. But I am unable to judge which files have to be downloaded and the links provided in that tutorial are not exactly taking me to the download page. – Korhan Feb 01 '13 at 06:21
  • @Korhan Download Mime4j from this link in zip format an take out jar from it and add it to your project : http://james.apache.org/download.cgi#Apache_Mime4J and similarly download the other 3 from here :http://hc.apache.org/downloads.cgi – Payal Feb 01 '13 at 06:27
  • @Payal I need to download Source (ZIP Format), Not Binary (ZIP Format). Right? – Korhan Feb 01 '13 at 06:33
  • @Payal I am able to find that three jar files in httpclient file, but in Mime4j, I am unable to find the .jar file with the exact name apache-mime4j-0.7.2.jar as my downloaded version is 0.7.2.BTW I had to download Binary (ZIP Format) not Source. – Korhan Feb 01 '13 at 06:56
  • @Payal Okay. Got it. In the comments it is mentioned to add pache-mime4j-core-0.7.jar. Thanks. – Korhan Feb 01 '13 at 07:12

3 Answers3

2

Have you considered using FTP instead of your present methodology? There is a library from apache called Apache's commons-net-ftp library to get the job done easily.

Using apache FTP library

Here is a question I asked on stackoverflow long time ago. I was implementing pretty much the same code before but I found FTP method is way easier for uploading files to server.

@TemporaryNickName How to send other data too along with that image. Moreover my image data is in bitmap, not an uri. How to implement it according to my present things?

*There are many tutorials that shows you how to convert bitmap to image file (This is pretty much method of saving file temporary and delete immediately after FTP is done), moreover, when you take a photo using default built in camera app, you image saves automatically. Well sending data should be done separately, in this case, I would write a PHP script with $_POST to receive data than save it into database or write it into XML*


To save uploaded file, use

move_uploaded_file($src, $path);

move uploaded file doc

Jason
  • 1,298
  • 1
  • 16
  • 27
2

To send multiple types of data use MultipartEntity (from link provided in your question) instead of URLEncodedEntity. The idea is that MultipartEntity just contains bodies of different types (such as StringBody, FileBody, etc.). So, if you need to send images in Base64, add them as StringBody to the MultipartEntity (which should be setted as entity of your request, using setEntity).

Although, I highly recommend you to save your bitmaps on disk (sd card) and use FileBody instead. It will save you a lot of memory (with Base64 you have to load all images at once) and... what if user will close your app while uploading? You'll lost your bitmaps forever.

P.S. Don't forget to use Service for uploading tasks.

Dmitry Zaytsev
  • 23,650
  • 14
  • 92
  • 146
  • Thanks and +1 for your time. Okay. I save my images on sd card and then provide the paths to make use of MultipartEntity because there would be no use if I still utilize that base64 to convert bitmap to string as it increases the data to be sent. But can you tell me suppose if I do entity.addPart("myIdentifier", new StringBody("stringvalue")); entity.addPart("myImageFile", new FileBody(imageFile)); entity.addPart("myAudioFile", new FileBody(audioFile)); like this how to get string values(eg, stringvalue) at php side? – Korhan Jan 29 '13 at 07:05
  • @Korhan as far as I remember files will be in `$_FILES` variable. In your case `$_FILES["myAudioFile"]["tmp_name"]` will be a temporary path to just uploaded file (and then you should move it somwhere else). Example provided in link in your quesiton ) – Dmitry Zaytsev Jan 29 '13 at 07:17
  • Yeah. I know about that. But I was asking about strings. Would $_POST[myIdentifier]; fetch me stringvalue? – Korhan Jan 29 '13 at 07:33
  • @Korhan I'm not really php developer, but I assuming that files will be in `$_FILES` and, yes, other data will be in `$_POST`. Give it a try ) – Dmitry Zaytsev Jan 29 '13 at 07:35
1

Here is my code snippet, Hope this helps :

private class AsyncTask1 extends AsyncTask<Void, Void, String>{




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

        boolean response = false;

        try {

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            FileBody bin = new FileBody(new File("temp"));

            File tempImg  = new File("sdcard/signature.jpg");
            if(tempImg.exists())
            {
                checkimgfile=checkimgfile+"LPA"+tempImg;
                bin = new FileBody(tempImg, "image/jpg");
                reqEntity.addPart("txt_sign_lpa", bin);
                reqEntity.addPart("count_lpa",new StringBody("1"));
            }
            else
            {
                reqEntity.addPart("count_lpa",new StringBody("0"));
            }

                FileBody bin1 = new FileBody(new File("temp"));
                File tempImg1  = new File("sdcard/signature2.jpg");
                if(tempImg1.exists())
                {

                    checkimgfile=checkimgfile+"subject"+tempImg1;
                    bin1 = new FileBody(tempImg1, "image/jpg");
                    reqEntity.addPart("txt_sign", bin1);
                    reqEntity.addPart("count_subject",new StringBody("1"));
                }




                reqEntity.addPart("count",new StringBody("0"));


            reqEntity.addPart("name",new StringBody("Shaili"));
            reqEntity.addPart("age",new StringBody("47"));




            try
            {


            ConnectivityManager cm =
            (ConnectivityManager)getBaseContext().getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();


            if(activeNetwork!=null && activeNetwork.isAvailable() && activeNetwork.isConnected())
            {
                String xml = "";
                HttpParams httpParameters = new BasicHttpParams();  
                HttpConnectionParams.setConnectionTimeout(httpParameters, 100000);
                HttpConnectionParams.setSoTimeout(httpParameters, 100000);
                final HttpClient httpclient = new DefaultHttpClient(httpParameters);
                final HttpPost httppost = new HttpPost("https://www.xyz.com/abc.php");//url where you want to post your data.
                httppost.setParams(httpParameters);


                httppost.setEntity(reqEntity);
                httppost.addHeader("Accept", "text/html");

                httppost.addHeader("Host", "www.xyz.com");
                httppost.addHeader("User-Agent",
                        "Android ");

                HttpResponse response1 = null;
                String errMessage = "Error";
                try {

                    response1 = httpclient.execute(httppost);
                    final HttpEntity resEntity = response1.getEntity();
                    InputStream content = resEntity.getContent();
                    BufferedReader b = new BufferedReader(new InputStreamReader(
                            content));
                    xml = XmlParser.getTrimmedResponse(b);

                    if (response1 != null){
                        if(Integer.toString(response1.getStatusLine().getStatusCode()).equals("200")){
                            return "success";
                        }
                    }



                } catch (Exception e) {


                    e.printStackTrace();
                    errorstring=errorstring+e.getLocalizedMessage();
                    errMessage = "Network error";

                    return errMessage;
                }

            }
            else if(activeNetwork==null)
            {

                return "Available";
            }

            }
            catch(Exception e)
            {

            Toast.makeText(getBaseContext(), "Network Connection not available", 1).show();
            progressDialog.dismiss();

            }


        } catch (Exception e) {

            errorstring=errorstring+e.getLocalizedMessage();
            return "Network error";

        }
        return "abc";
    }       

    protected void onPostExecute(String result) {


    //do your stuff

    }
}
Payal
  • 903
  • 1
  • 9
  • 28