这是主函数 package com.zmb.updemo; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.UUID; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; public class MainActivity extends Activity implements OnClickListener{ private Button mBtnUpload,whether; private ProgressBar mPgBar; private TextView mTvProgress; private Button choose; private ImageView imageView; private File file; private UpLoadTask upLoadTask; private static final int TIME_OUT = 120*10000000; //超时时间 private static final String CHARSET = "utf-8"; //设置编码 private static final String RequestURL="http://192.168.0.164:9580/ekp/TestServlet"; private AlertDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBtnUpload = (Button)findViewById(R.id.uploadImage); choose = (Button)findViewById(R.id.selectImage); imageView=(ImageView) findViewById(R.id.imageView); mBtnUpload.setOnClickListener(this); choose.setOnClickListener(this); View upView = getLayoutInflater().inflate(R.layout.progress_bar_item, null); mPgBar = (ProgressBar)upView.findViewById(R.id.pb_filebrowser_uploading); mTvProgress = (TextView)upView.findViewById(R.id.tv_filebrowser_uploading); whether = (Button)upView.findViewById(R.id.upload_over); whether.setOnClickListener(this); dialog=new AlertDialog.Builder(MainActivity.this).setView(upView).create(); } private class UpLoadTask extends AsyncTask<Void, Integer, String>{ @Override protected void onPostExecute(String result) { mTvProgress.setText(result); whether.setText("确定"); } @Override protected void onPreExecute() { dialog.show(); mTvProgress.setText("正在上传图片..."); whether.setText("取消"); } @Override protected void onProgressUpdate(Integer... values) { Integer num=values[0]; mPgBar.setProgress(num); mTvProgress.setText("正在上传图片..." + num + "%"); } @Override protected String doInBackground(Void...parem) { String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成 String PREFIX = "--" , LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; //内容类型 try { URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); conn.setDoInput(true); //允许输入流 conn.setDoOutput(true); //允许输出流 conn.setUseCaches(false); //不允许使用缓存 conn.setRequestMethod("POST"); //请求方式 conn.setRequestProperty("Charset", CHARSET); //设置编码 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if(file!=null) { /** * 当文件不为空,把文件包装并且上传 */ OutputStream outputSteam=conn.getOutputStream(); DataOutputStream dos = new DataOutputStream(outputSteam); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * 这里重点注意: * name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件 * filename是文件的名字,包含后缀名的 比如:abc.png */ sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END); sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); InputStream fis = new FileInputStream(file); long total = fis.available(); String totalstr = String.valueOf(total); Log.d("文件大小", totalstr); byte[] buffer = new byte[8192]; // 8k int count = 0; int length = 0; while ((count = fis.read(buffer)) != -1) { dos.write(buffer, 0, count); length += count; publishProgress((int) ((length / (float) total) * 100)); //为了演示进度,休眠50毫秒 Thread.sleep(50); } fis.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes(); dos.write(end_data); dos.flush(); /** * 获取响应码 200=成功 * 当响应成功,获取响应的流 */ int res = conn.getResponseCode(); if(res==200) { return "上传成功!"; } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return "上传失败!"; } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onClick(View v) { int id=v.getId(); switch (id) { case R.id.selectImage: /*** * 这个是调用android内置的intent,来过滤图片文件 ,同时也可以过滤其他的 */ Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); //回调图片类使用的 startActivityForResult(intent, RESULT_CANCELED); break; case R.id.upload_over: if("确定".equals(whether.getText()+"")){ dialog.dismiss(); }else{ upLoadTask.cancel(true); dialog.dismiss(); } break; default: /* //这里的view是上传进度的弹框 //AsyncTask的实例 upLoadTask=new UpLoadTask(); upLoadTask.execute();*/ HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet("http://192.168.0.164:9580/ekp/TestServlet"); try { HttpResponse response = client.execute(get); BufferedReader reader = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); for (String s = reader.readLine(); s != null; s = reader.readLine()) { System.out.println("------------------??????"); } } catch (Exception e) { e.printStackTrace(); } break; } } /** * 回调执行的方法 */ @SuppressWarnings("deprecation") @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode==Activity.RESULT_OK) { /** * 当选择的图片不为空的话,在获取到图片的途径 */ Uri uri = data.getData(); try { String[] pojo = {MediaStore.Images.Media.DATA}; Cursor cursor = managedQuery(uri, pojo, null, null,null); if(cursor!=null) { ContentResolver cr = this.getContentResolver(); int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String path = cursor.getString(colunm_index); /*** * 这里加这样一个判断主要是为了第三方的软件选择,比如:使用第三方的文件管理器的话,你选择的文件就不一定是图片了,这样的话,我们判断文件的后缀名 * 如果是图片格式的话,那么才可以 */ if(path.endsWith("jpg")||path.endsWith("png")) { file=new File(path); Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri)); imageView.setImageBitmap(bitmap); } } } catch (Exception e) { e.printStackTrace(); } } /** * 回调使用 */ super.onActivityResult(requestCode, resultCode, data); } }
主配置文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="选择图片" android:id="@+id/selectImage" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="上传图片" android:id="@+id/uploadImage" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" /> </LinearLayout>
还有一个进度条的配置文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" > <ProgressBar android:id="@+id/pb_filebrowser_uploading" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content"/> <TextView android:id="@+id/tv_filebrowser_uploading" android:layout_width="match_parent" android:layout_height="wrap_content"/> <Button android:id="@+id/upload_over" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout>