如何使用post方法将简单图像从Android发布到服务器

时间:2013-11-22 05:34:36

标签: java android

如何在Android

中发布图片
  • 我是新手&我正在寻找如何分步说明 发布图像发生在android
  • 互联网上是否有任何良好的信息来源可供学习 此
  • 我想要学习的是从imageview获取图像并发布 到服务器

我尝试了什么

我已经学会了将字符串发布到服务器


以下是我如何将srtings发布到服务器

activity_main.xml中

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

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

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/imageView1"
        android:text="Click to upload Image"
        android:textSize="15dp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/NAME_EDIT_TEXT_ID"
        android:layout_alignParentLeft="true"
        android:clickable="false"
        android:text="NAME"
        android:textSize="20dp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/NAME_EDIT_TEXT_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/CITY_EDIT_TEXT_ID"
        android:layout_alignRight="@+id/button1"
        android:layout_marginBottom="30dp"
        android:ems="10" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/CITY_EDIT_TEXT_ID"
        android:layout_alignLeft="@+id/textView2"
        android:clickable="false"
        android:text="CITY"
        android:textSize="20dp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/CITY_EDIT_TEXT_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/NAME_EDIT_TEXT_ID"
        android:layout_centerVertical="true"
        android:ems="10" />

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

</RelativeLayout>

MainActivity.java

public class MainActivity extends Activity {

    Button submit;
    EditText name, City;
    ProgressDialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        submit = (Button) findViewById(R.id.SUBMIT_BUTTON_ID);
        name = (EditText) findViewById(R.id.NAME_EDIT_TEXT_ID);
        City = (EditText) findViewById(R.id.CITY_EDIT_TEXT_ID);

        submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new MainTest().execute();


            }
        });
    }


    public void postData() {
        // Create a new HttpClient and Post Header

        // You can use NameValuePair for add data to post server and yes you can
        // also append your desire data which you want to post server.

        // Like:
        // yourserver_url+"name="+name.getText().toString()+"city="+City.getText().toString()

        String newurl = "?" + "Key=" + name.getText().toString();
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://My-URL"+newurl);

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("Name", name.getText()
                    .toString()));
            nameValuePairs.add(new BasicNameValuePair("city", City.getText()
                    .toString()));
            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) {

            postData();

            return null;
        }

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

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

        }

    }

}

现在我如何修改代码以便从imageview获取图像并将其发送到服务器?

  • 任何指导都会有所帮助
  • 我是新手,所以请轻松解答

感谢

2 个答案:

答案 0 :(得分:4)

以下是一个场景,指示图像如何从一种格式转换为另一种格式,最后返回原始格式。

enter image description here

尝试以下代码

Android方

private void uploadToServer(byte[] data) {
    Bitmap bitmapOrg = BitmapFactory.decodeByteArray(data, 0, data.length);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
    byte[] ba = bao.toByteArray();
    String ba1 = Base64.encodeBytes(ba);
    final ArrayList<NameValuePair> nameValuePairs = new
    ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("image", ba1));
    Thread t = new Thread() {
        @Override
        public void run() {
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new
                HttpPost("http://www.yoururl.com");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                // HttpEntity entity = response.getEntity();

                // is = entity.getContent();
                // String the_string_response =
                // convertResponseToString(response);
                // Log.e("log_tag", "Image Uploaded  "+the_string_response);
            } catch (Exception e) {
                Log.e("log_tag", "Error in http connection " + e.toString());
            }
        }
    };

}

服务器端

<?php

$base=$_REQUEST['image'];

echo $base;

// base64 encoded utf-8 string

$binary=base64_decode($base);

// binary, utf-8 bytes

header('Content-Type: bitmap; charset=utf-8');

// print($binary);

//$theFile = base64_decode($image_data);

$file = fopen('test.jpg', 'wb');

fwrite($file, $binary);

fclose($file);

echo '<img src=test.jpg>';

?>

Complete Tutorial

答案 1 :(得分:1)

You have use multi part to post images to the server from android
public static JSONObject  multiPart(final String url,Bitmap bm) throws Exception 
    {
        HttpResponse response = null ;
        InputStream is = null;
        BufferedReader in = null;
        JSONObject jObject = null;
        HttpPost httppost = new HttpPost(url);
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        HttpClient httpClient = getHttpClient();
        if(bm!=null){
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bm.compress(CompressFormat.PNG, 75, bos);
            byte[] data = bos.toByteArray();
            ByteArrayBody bab = new ByteArrayBody(data, name+".png");
            entity.addPart("file", bab);
        }

        httppost.setEntity(entity);
        try {
            response =  httpClient.execute(httppost);
             HttpEntity resEntity = response.getEntity();

            is = resEntity.getContent();
            in = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),
                    1024 * 4);
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String result = "";
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            result = sb.toString();

            jObject = new JSONObject(result);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
         //   e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
         //   e.printStackTrace();
        }

     finally {
        in.close();

    }
    // jObject.getString(name);
     return jObject;
    }

首先将图像转换为位图,然后将位图传递给此方法。并且不要忘记将以下jar添加到库中: - httpmime-4.2-beta1.jar,apache-mime4j-0.6.1.jar