从android发送单个图像到服务器

时间:2013-12-05 04:56:03

标签: android

我正在尝试将单个图像发布到服务器


  • 我正在进行 POST 请求
  • 当我发布帖子请求时,图像不会发送到服务器(我 检查服务器)

我尝试了什么::

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

        }

    }

}

我该如何解决?


[编辑]

我检查服务器是否正常运行以接受图像,但它看起来运行得很好!当使用postman-tool检查上传图片时,问题必须是客户端部分

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

        }

    }

}

2 个答案:

答案 0 :(得分:2)

您必须使用MultipartEntity将图像上传到服务器

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

答案 1 :(得分:0)

你可以尝试一下。

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