Java 如何使用post方法将简单图像从Android发布到服务器 安卓系统中图像发布的工作原理 我是一个新手&我正在寻找一个如何一步一步的指导 在安卓系统中发布图片 互联网上有什么好的信息来源可以学习吗 这个 我所要学的就是从imageview中获取一张图片并发布它 到服务器

Java 如何使用post方法将简单图像从Android发布到服务器 安卓系统中图像发布的工作原理 我是一个新手&我正在寻找一个如何一步一步的指导 在安卓系统中发布图片 互联网上有什么好的信息来源可以学习吗 这个 我所要学的就是从imageview中获取一张图片并发布它 到服务器,java,android,Java,Android,我试过什么 我已经学会了向服务器发送字符串 下面是我如何将SRTING发布到服务器的 活动\u 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_heig

我试过什么

我已经学会了向服务器发送字符串


下面是我如何将SRTING发布到服务器的 活动\u 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();

        }

    }

}
公共类MainActivity扩展活动{
按钮提交;
编辑文本名称,城市;
ProgressDialog;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submit=(按钮)findViewById(R.id.submit\u按钮\u id);
name=(EditText)findViewById(R.id.name\u EDIT\u TEXT\u id);
城市=(编辑文本)findViewById(R.id.City\u EDIT\u TEXT\u id);
submit.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
新建MainTest().execute();
}
});
}
public void postData(){
//创建一个新的HttpClient和Post头
//您可以使用NameValuePair向post服务器添加数据,是的,您可以
//还附加您想要发布到服务器上的所需数据。
//比如:
//yourserver_url+“name=“+name.getText().toString()+”city=“+city.getText().toString())
字符串newurl=“?”+“Key=“+name.getText().toString();
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://My-URL“+新网址);
试一试{
//添加您的数据
List nameValuePairs=新的ArrayList(2);
添加(新的BasicNameValuePair(“Name”,Name.getText())
.toString());
添加(新的BasicNameValuePair(“城市”,city.getText())
.toString());
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
//执行HTTP Post请求
HttpResponse response=httpclient.execute(httppost);
Log.v(“Response”,Response.toString());
}捕获(客户端协议例外e){
//TODO自动生成的捕捉块
}捕获(IOE异常){
//TODO自动生成的捕捉块
}
}
公共类MainTest扩展了异步任务{
@凌驾
受保护的void onPreExecute(){
pDialog=新建进度对话框(MainActivity.this);
pDialog.setMessage(“加载…”);
pDialog.setUndeterminate(真);
pDialog.setCancelable(假);
pDialog.show();
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
postData();
返回null;
}
@凌驾
受保护的void onPostExecute(字符串结果){
//TODO自动生成的方法存根
super.onPostExecute(结果);
//data=jobj.toString();
pDialog.disclose();
}
}
}

现在,我如何修改代码,以便从
imageview
获取图像并将其发送到服务器?
  • 任何指导都会有帮助
  • 我是新手,所以请轻松回答
谢谢

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添加到libs:-httpmime-4.2-beta1.jar,apache-mime4j-0.6.1.jar


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

下面是一个场景,说明图像如何从一种格式转换为另一种格式,最后返回到原始格式

尝试以下代码

安卓端

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

}
private void uploadToServer(字节[]数据){
位图bitmapOrg=BitmapFactory.decodeByteArray(数据,0,数据.length);
ByteArrayOutputStream bao=新建ByteArrayOutputStream();
压缩(Bitmap.CompressFormat.JPEG,90,bao);
字节[]ba=bao.toByteArray();
字符串ba1=Base64.encodeBytes(ba);
最终ArrayList nameValuePairs=新建
ArrayList();
添加(新的BasicNameValuePair(“图像”,ba1));
线程t=新线程(){
@凌驾
公开募捐{
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新
HttpPost(“http://www.yoururl.com");
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpclient.execute(httppost);
//HttpEntity=response.getEntity();
//is=entity.getContent();
//字符串\u字符串\u响应=
//convertResponseToString(响应);
//Log.e(“日志标签”、“上传图像”+字符串响应);
}捕获(例外e){
e(“Log_标记”,“http连接错误”+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>';

?>


以下是一个场景,说明图像如何从一种格式转换为另一种格式,最后再转换回原始格式

尝试以下代码

安卓端

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

}
private void uploadToServer(字节[]数据){
位图bitmapOrg=BitmapFactory.decodeByteArray(数据,0,数据.length);
ByteArrayOutputStream bao=新建ByteArrayOutputStream();
压缩(Bitmap.CompressFormat.JPEG,90,bao);
字节[]ba=bao.toByteArray();