如何将捕获的图像发送到服务器?

Hi i am developing an app which includes camera images, i need to send images while capturing to php server, in our settings there is boolean option as "AutoUploadPic" when we set the switch to yes, then only it should upload to server, if it set to no it should not upload. can you please help me out from this.

The following is iphone code for above query, can i get as the same for android.

Why can't you convert your bitmap into byte array and pass that to your server. Here is the code to send a bitmap to the server?

Please do these stuffs in AsyncTask.

public class UploadPicture extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        // show your progress bar

    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub

        // wrap up all your upload code here..

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        // stop your progress bar
    }
}

Call this class after checking your boolean :

 if(AutoUploadPic)
{
new UploadPicture().execute();
}
else
{
// Your code here..
}

// do the following in the doInBackground Class :

    try {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

// Preview_bitmap is the one you need to send to the server. I'm compressing here and sending this to server:

    preview_bitmap.compress(CompressFormat.JPEG, 100, bos);
    byte[] data = bos.toByteArray();

    HttpClient httpClient = new DefaultHttpClient();

// constant.uploadImagesAPI is the your server URL :

    HttpPost postRequest = new HttpPost(Constant.uploadImagesAPI
            + Constant.mDeviceID);

    ByteArrayBody bab = new ByteArrayBody(data, ".jpg");
    MultipartEntity reqEntity = new MultipartEntity(
            HttpMultipartMode.BROWSER_COMPATIBLE);
    reqEntity.addPart("image", bab);
    postRequest.setEntity(reqEntity);
    HttpResponse response = httpClient.execute(postRequest);
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            response.getEntity().getContent(), "UTF-8"));
    String sResponse;
    StringBuilder mUploadResponse = new StringBuilder();

    while ((sResponse = reader.readLine()) != null) {
        mUploadResponse = mUploadResponse.append(sResponse);
    }

    JSONObject mUploadResponseObject = new JSONObject(
            mUploadResponse.toString());

    mUploadResponseObject.getJSONArray("response");

    try {
        JSONArray jsonArray = mUploadResponseObject
                .getJSONArray("response");
        for (int i = 0; i < jsonArray.length(); i++) {
            uploadStatus = jsonArray.getJSONObject(i)
                    .getJSONObject("send").getString("message");
            uploadPhotoID = jsonArray.getJSONObject(i)
                    .getJSONObject("send").getString("id");
            Constant.imageUploadedFlag = true;
        }
    } catch (Exception e) {
        serverUploadException = true;

    }

} catch (Exception e) {

}

// PHP code :

   $to = $_REQUEST['deviceid'];
            //$timestamp = $_REQUEST['timestamp'];
            $path=PATH.'upload/';
            //$path1=PATH.'newupload/';
            //$name = $_FILES['image']['name'];
            //$str=explode(".",$name);
            //$imname=$str[0];
            $filename=upload::save($_FILES['image']);                   
            $file_name1= basename($filename);
            $docroot= $_SERVER['DOCUMENT_ROOT'];    
            //$root=$docroot.'/newupload/';
            $roots=$docroot.'/upload/';
            $url = $path.$file_name1;   
                        $send = $this->api->upload_images($to,$url);
                    if($send)
                                {



                                         $json_response[] = array("send" => 
                                               array("id"=> $send,
                                            "message"=>"Message Sent Successfully",
                                             "status"=>1));
                                                             }  
                                                              echo json_encode(array ('response'  =>$json_response));


        break; 

Upload Image to server via multipart file upload.

import java.io.File;
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.content.res.Resources.NotFoundException;
import android.os.AsyncTask;


public class MultiPartFileUpload {

    private String filePath;
    private String fileMimeType;
    private String url;
    private String attribute;
    private AfterImageUploaded afterResult;
    private CustomExceptions exception = null;
    byte[] buffer;
    byte[] data;
    private Context context;
    /**
     * Provide mechanism to upload file with multi-part approach
     * 
     * @param filePath
     *            : Absolute path of file
     * @param fileMimeType
     *            : File mime-type e.g. image/jpeg
     * @param url
     *            : URL to upload file
     * @param attribute
     *            : Attribute where file would be placed
     * @param afterResult
     *            : Implement this interface to receive result/errors
     */
    public MultiPartFileUpload(Context context,String filePath, String fileMimeType,
            String url, String attribute, AfterImageUploaded afterResult) {
        this.context=context;
        this.filePath = filePath;
        this.fileMimeType = fileMimeType;
        this.url = url;
        this.attribute = attribute;
        this.afterResult = afterResult;

        UploadFileAsync uploadasynctask = new UploadFileAsync();
        uploadasynctask.execute(url);
    }

    class UploadFileAsync extends AsyncTask<String, Integer, String> {

        @Override
        protected void onProgressUpdate(Integer... values) {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values[0]);
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                String result = null;
                ContentBody cbFile = null;
                HttpClient httpclient = new DefaultHttpClient();

                System.out.println("url:"+url);

                HttpPost httppost = new HttpPost(url);

                httppost.setHeader("partnerKey",
                                   "39f1a112ed3b4a3537c1e05766e91d2f425a8d97");


                MultipartEntity mpEntity = new MultipartEntity();
                mpEntity.addPart("image",  new FileBody(new File(filePath)));
                        }



                try {
                    httppost.setEntity(mpEntity);

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



                System.out.println("response>>>>::"+ response.getStatusLine());
                    System.out.println("--------------------------------------");

                    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                        if (resEntity != null) {
                            result = EntityUtils.toString(resEntity);
                        }

                    } else {
                        throw new CustomExceptions("Connection error: "
                                + response.getStatusLine().getStatusCode()
                                + ":" + response.getStatusLine());
                    }
                } catch (ClientProtocolException e) {
                    throw new CustomExceptions("Protocol Exception");
                } catch (ParseException e) {
                    throw new CustomExceptions("Parse Exception");
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new CustomExceptions("IO Exception");
                }

                httpclient.getConnectionManager().shutdown();

                return result;


                //  return postFile(); publishProgress(10)

            }  catch (NotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


            return null;}

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            afterResult.doAfterResult(result, exception);
        }

    }

    public interface AfterImageUploaded {
        public void doAfterResult(String result, Exceptions e);
    }

}