2

I am a newbie to android. How can I send text data along with image using multipart post method to server? I can now send image along with name to server. I have to send String data1 and data2 along with this.

code is given below

public class UploadToServerNew extends Activity {

    TextView messageText;
    Button uploadButton;
    int serverResponseCode = 0;
    private static final int SELECT_PHOTO = 100;

    String upLoadServerUri = null;

    /**********  File Path *************/

    Uri selectedImage;
    String pathtoimage;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_to_server);

        uploadButton = (Button)findViewById(R.id.uploadButton);
        messageText  = (TextView)findViewById(R.id.messageText);



        /************* Php script path ****************/
        upLoadServerUri = "http://192.168.1.23/imagetransfer/UploadToServer.php";


        uploadButton.setOnClickListener(new OnClickListener() {            
            @Override
            public void onClick(View v) {

                Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                photoPickerIntent.setType("image/*");
                startActivityForResult(photoPickerIntent, SELECT_PHOTO); 



                }
            });
    }
    private String getRealPathFromURI(Uri contentURI) {
        String result;
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) { // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else { 
            cursor.moveToFirst(); 
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

        switch(requestCode) { 
        case SELECT_PHOTO:
            if (resultCode == RESULT_OK) {
                selectedImage = imageReturnedIntent.getData();

                pathtoimage = getRealPathFromURI(selectedImage);
                new uploadFile().execute(pathtoimage);
                Log.d("path", pathtoimage);

            }
        }
    }
    private class uploadFile extends AsyncTask<String, Void, Void>{
        ProgressDialog dialog;
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            messageText.setText("");
            dialog = ProgressDialog.show(UploadToServerNew.this, "", "Uploading file...", true);
            dialog.show();
        }
        @Override
        protected Void doInBackground(String... pathtoimage) {
            // TODO Auto-generated method stub
             uploadFile(pathtoimage[0]);      
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if(dialog.isShowing()){
                dialog.dismiss();
            }
        }
    }

    public int uploadFile(String sourceFileUri) {


          String fileName = sourceFileUri;
          String data1="one",data2="two";

          HttpURLConnection conn = null;
          DataOutputStream dos = null;  
          String lineEnd = "\r\n";
          String twoHyphens = "--";
          String boundary = "*****";
          int bytesRead, bytesAvailable, bufferSize;
          byte[] buffer;
          int maxBufferSize = 1 * 1024 * 1024; 
          File sourceFile = new File(sourceFileUri); 


               try { 

                     // open a URL connection to the Servlet
                   FileInputStream fileInputStream = new FileInputStream(sourceFile);
                   URL url = new URL(upLoadServerUri);

                   // Open a HTTP  connection to  the URL
                   conn = (HttpURLConnection) url.openConnection(); 
                   conn.setDoInput(true); // Allow Inputs
                   conn.setDoOutput(true); // Allow Outputs
                   conn.setUseCaches(false); // Don't use a Cached Copy
                   conn.setRequestMethod("POST");
                   conn.setRequestProperty("Connection", "Keep-Alive");
                   conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                   conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                   conn.setRequestProperty("uploaded_file", fileName); 

                   dos = new DataOutputStream(conn.getOutputStream());

                   dos.writeBytes(twoHyphens + boundary + lineEnd); 
                   dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                             + fileName + "\"" + lineEnd);

                   dos.writeBytes(lineEnd);

                   // create a buffer of  maximum size
                   bytesAvailable = fileInputStream.available(); 

                   bufferSize = Math.min(bytesAvailable, maxBufferSize);
                   buffer = new byte[bufferSize];

                   // read file and write it into form...
                   bytesRead = fileInputStream.read(buffer, 0, bufferSize);  

                   while (bytesRead > 0) {

                     dos.write(buffer, 0, bufferSize);
                     bytesAvailable = fileInputStream.available();
                     bufferSize = Math.min(bytesAvailable, maxBufferSize);
                     bytesRead = fileInputStream.read(buffer, 0, bufferSize);   

                    }

                   // send multipart form data necesssary after file data...
                   dos.writeBytes(lineEnd);
                   dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                   // Responses from the server (code and message)
                   serverResponseCode = conn.getResponseCode();
                   String serverResponseMessage = conn.getResponseMessage();

                   Log.i("uploadFile", "HTTP Response is : " 
                           + serverResponseMessage + ": " + serverResponseCode);

                   if(serverResponseCode == 200){

                       runOnUiThread(new Runnable() {
                            public void run() {

                                String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                              +"http://localhost/imagetransfer/uploads/";

                                messageText.setText(msg);
                                Toast.makeText(UploadToServerNew.this, "File Upload Complete.", 
                                             Toast.LENGTH_SHORT).show();
                            }
                        });                
                   }    

                   //close the streams //
                   fileInputStream.close();
                   dos.flush();
                   dos.close();

              } catch (MalformedURLException ex) {

                //  dialog.dismiss();  
                  ex.printStackTrace();

                  runOnUiThread(new Runnable() {
                      public void run() {
                          messageText.setText("MalformedURLException Exception : check script url.");
                          Toast.makeText(UploadToServerNew.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                      }
                  });

                  Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
              } catch (Exception e) {

               //   dialog.dismiss();  
                  e.printStackTrace();

                  runOnUiThread(new Runnable() {
                      public void run() {
                          messageText.setText("Got Exception : see logcat ");
                          Toast.makeText(UploadToServerNew.this, "Got Exception : see logcat ", 
                                  Toast.LENGTH_SHORT).show();
                      }
                  });
                  Log.e("Upload file to server Exception", "Exception : " 
                                                   + e.getMessage(), e);  
              }
             // dialog.dismiss();       
              return serverResponseCode; 


         } 

}
2
  • Please see the answer on : stackoverflow.com/questions/22138881/… Commented May 5, 2014 at 9:21
  • My above code is working fine.But I have to send two more text stings data1 and data2 along with it. Pls help me out. Commented May 5, 2014 at 9:36

5 Answers 5

3

Sending text and image to server is an easy task..just you convert the image into string and send along with text..

       Bitmap bitmap = BitmapFactory.decodeFile(fileUri);

       ByteArrayOutputStream stream = new ByteArrayOutputStream();

       bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);


       byte[]  byteArray= stream.toByteArray();
       String  imageString= Base64.encode(byteArray);


      ArrayList<NameValuePair> ValuePairs= newArrayList<NameValuePair>(); 
      ValuePairs .add(new BasicNameValuePair("image", imageString));
      ValuePairs .add(new BasicNameValuePair("imageName", Name));

      ValuePairs .add(new BasicNameValuePair("FolderId", folder));

      try 
      {
         HttpClient httpclient = new DefaultHttpClient();
         HttpPost httppost =new HttpPost("http://64.125.119.152:1991/uploadserver/UploadToServer.php");              
        System.setProperty("http.keepAlive", "false");
        httppost .setEntity(new UrlEncodedFormEntity(ValuePairs ));
        HttpResponse response = httpclient.execute(httppost );
        Strresponse= convertResponseToString(response );

        }
   catch (Exception e)

    {
     Toast.makeText(s, "ERROR " + e.getMessage(),       
     Toast.LENGTH_LONG).show();
     System.out.println("Error in http connection " + e.toString());
    }

 return Strresponse;
} //*visit:http://androiddhina.blogspot.in/p/androidhints.html  */
Sign up to request clarification or add additional context in comments.

Comments

1

You can try something like this:

conn.setRequestProperty("uploaded_file", fileName);
conn.setRequestProperty("key_1", "value_1"); 
conn.setRequestProperty("key_2", "value?_2"); 
conn.setRequestProperty("key_3", "value_3"); 

conn.setRequestProperty("key_n", "value_n"); 

where key__1,2,3, n is data1, data2, datan ....

EDITED

and at server side in php:

You can use this $_SERVER["key_1"] or $_SERVER["key_2"] .... $_SERVER["key_n"] ;

3 Comments

still no chance..Sure about android part?
conn.setRequestProperty("data1", data1); conn.setRequestProperty("data2", data2); also included
Use $_SERVER['data1'] instead of $_POST['data1'];, it will work.
0

Try using HTTP Request library. To perform multipart post you only need to do is:

HttpRequest request = HttpRequest.post("http://google.com");
request.part("status[body]", "Making a multipart request");
request.part("status[image]", new File("/home/kevin/Pictures/ide.png"));
if (request.ok())
  System.out.println("Status was updated");

Comments

0

You can try this :

THIS IS YOUR CODE
.......

dos.writeBytes(twoHyphens + boundary + lineEnd); 
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);

// add code below ...
// start from here ............  

dos.writeBytes(twoHyphens + boundary + lineEnd); 
dos.writeBytes("Content-Disposition: form-data; name=\"YOUR VARIABLE NAME\"" + lineEnd + lineEnd + "YOUR DATA VALUE" + lineEnd);

// end .............  

THIS IS YOUR CODE

dos.writeBytes(lineEnd);

...........

Comments

0

Just use below method here:

    Button btn_update = view.findViewById(R.id.btn_update);
    btn_update.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {                    
               if (Util.isConnectingToInternet(getActivity())) {
                    updateProfileDetails();
                } else {
                  // No Internet Connection code here
                }    
        }
    });

    private String imagePath;
    ProgressDialog pDialog;
    AlertDialog.Builder builder;

    public void updateProfileDetails() {
        new AsyncTask<Void, Integer, String>(){
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(getActivity());
                pDialog.setTitle("Please wait");
                pDialog.setMessage("updating.... ");
                pDialog.setCancelable(false);
                pDialog.show();
                builder = new AlertDialog.Builder(getActivity());
            }

            @Override
            protected String doInBackground(Void... voids) {
                return uploadFile();
            }

            private String uploadFile(){
                File uploadFile1 = new File(imagePath);
                File uploadFile2 = new File(imagePath);
                String logId = applicationController.getValueFromPerference(Constants.LOGID);

                String responseString = null;

                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(Constants.URL + Constants.UPDATE_PROFILE);
                try {
                    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
                    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                    entityBuilder.addTextBody("companyname", companyName);
                    entityBuilder.addTextBody("name", name);
                    entityBuilder.addTextBody("phone", mobileNo);
                    entityBuilder.addTextBody("email", emailId);
                    entityBuilder.addTextBody("dateofbirth", dateOfBirth);
                    entityBuilder.addTextBody("aadharnumber", aadhaarCardNo);
                    entityBuilder.addTextBody("pannumber", pancardNo);
                    entityBuilder.addTextBody("address", address);
                    entityBuilder.addTextBody("location", location);
                    entityBuilder.addTextBody("pincode", pincode);
                    entityBuilder.addTextBody("logid", logId);

                    entityBuilder.addBinaryBody("userimage", uploadFile1);
                    entityBuilder.addBinaryBody("gumasta", uploadFile2);

                    HttpEntity entity = entityBuilder.build();
                    httppost.setEntity(entity);

                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity  httpEntity = response.getEntity();

                    int statusCode = response.getStatusLine().getStatusCode();
                    if (statusCode == 200) {
                        // Server response
                        responseString = EntityUtils.toString(httpEntity);
                    } else {
                        responseString = "Error occurred! Http Status Code: "
                                + statusCode;
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                return responseString;
            }

            @Override
            protected void onPostExecute(String resultString) {
                super.onPostExecute(resultString);
                if (pDialog.isShowing())
                    pDialog.dismiss();
                Toast toast = Toast.makeText(context, resultString, Toast.LENGTH_LONG);
                toast.getView().setBackgroundColor(getResources().getColor(R.color.nevy_blue));
                toast.show();
                if (resultString != null && !resultString.equals("")) {
                    try {
                        JSONObject jsonObject = new JSONObject(resultString);
                        if (jsonObject.getString("status").equals("1")) {
                            builder.setCancelable(true);
                            builder.setMessage(jsonObject.getString("message"));
                            builder.setInverseBackgroundForced(true);
                            builder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            builder.show();

                        } else {
                            Toast toast1 = Toast.makeText(context, jsonObject.getString("message"), Toast.LENGTH_LONG);
                            toast1.getView().setBackgroundColor(getResources().getColor(R.color.green));
                            toast1.show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                } else {
                    Toast toast2 = Toast.makeText(context, "Sorry! Due to some problem Message sending failed", Toast.LENGTH_LONG);
                    toast2.getView().setBackgroundColor(getResources().getColor(R.color.red));
                    toast2.show();
                }
            }

        }.execute();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.