获取权限
<uses-permission android:name="android.permission.CAMERA"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
页面布局视图:
效果是:点击图片1:拍照上传,1张或多张。
点击图片2:从相册中选择照片上传
Activity核心代码:
import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.GridLayout; import android.widget.ImageView; import android.widget.LinearLayout; import com.example.utils.BitMapUtils; import com.example.utils.FileUtils; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; public class UpLoadActivity extends Activity implements View.OnClickListener{ private ImageView image1,image2; private GridLayout showImagePanal; private EditText inMessage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_up_load); image1=(ImageView)findViewById(R.id.imageOne); image2=(ImageView)findViewById(R.id.imageTwo); showImagePanal=(GridLayout)findViewById(R.id.showImagePanal); inMessage=(EditText)findViewById(R.id.userMessage); image1.setOnClickListener(this); image2.setOnClickListener(this); } //点击图像,选择图片 @Override public void onClick(View v) { switch (v.getId()) { case R.id.imageOne: Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent1, 0); break; case R.id.imageTwo: Intent intent2=new Intent(); intent2.setAction(Intent.ACTION_GET_CONTENT); intent2.setType("image/*"); startActivityForResult(intent2, 1); break; default: break; } } private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); //记录已经拍摄或者选择的图像集 private List images=new ArrayList(); //接收返回的结果 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode==RESULT_OK){ switch (requestCode) { case 0: Bundle bundle = data.getExtras();//获取相机拍照后返回值 Bitmap bitmap = (Bitmap) bundle.get("data");//获取拍照图像 String fileName = "IMG_" + sdf.format(new Date()) + ".jpg"; String path = getApplicationContext().getCacheDir() .getAbsolutePath() + "/images/" + fileName; FileOutputStream b = null; File file = new File(path); if (!file.getParentFile().exists()) file.getParentFile().mkdirs();// 创建文件夹 try { b = new FileOutputStream(path); bitmap.compress(Bitmap.CompressFormat.JPEG, 60, b); b.flush(); b.close(); } catch (Exception e) { e.printStackTrace(); } Log.i("-------------", "path:" + path); images.add(path);//记录文件路径 //bitmap = BitMapUtils.getSmallBitmap(path); //image1.setImageBitmap(bitmap); break; case 1: Uri uri = data.getData();//获取选择的图片Uri String path2 = FileUtils.getPath(this, uri);//获取图片真实保存位置 images.add(path2);//记录文件路径 //Bitmap bitmap2 = BitMapUtils.getSmallBitmap(path2);//获取压缩图像 //image2.setImageBitmap(bitmap2); break; default: break; } } if(requestCode==1 || requestCode==0){ ImageView image=new ImageView(this); image.setId(images.size()+1); image.setLayoutParams(new LinearLayout.LayoutParams(80, 80)); Bitmap bitmap = BitMapUtils.getSmallBitmap(images.get(images.size()-1)+"");//获取压缩图像 image.setImageBitmap(bitmap); showImagePanal.addView(image); } } //发布 HttpURLConnection conn=null; public void doSend(View view){ Log.i("-------------", "--------start---------"); new Thread(new Runnable() { public void run() { String msg = inMessage.getText().toString(); String path="Http://10.0.2.2:8080/Web_Project/UploadImageServlet?inputMessage="+msg; try { URL url = new URL(path); String result = null; String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成; String PREFIX = "--", LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; // 内容类型 HttpURLConnection conn = (HttpURLConnection) url .openConnection(); conn.setReadTimeout(25000); conn.setConnectTimeout(5000); conn.setDoInput(true); // 允许输入流 conn.setDoOutput(true); // 允许输出流 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); // 请求方式 conn.setRequestProperty("Charset", "UTF-8"); // 设置编码 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if (images != null&&images.size()>0) { DataOutputStream dos = new DataOutputStream(conn .getOutputStream()); for (int i = 0; i < images.size(); i++) { File file=new File(images.get(i).toString()); Log.i("--------------------", "file"+i+"="+file.getName()); /** * 当文件不为空,把文件包装并且上传 */ 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=\"uimages\"; filename=\"" + file.getName() + "\"" + LINE_END); sb.append("Content-Type: application/octet-stream; charset=UTF-8" + LINE_END); sb.append(LINE_END); Log.i("------------", "--Header--"+sb.toString()); dos.write(sb.toString().getBytes()); InputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { dos.write(bytes, 0, len); } is.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) { InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); Log.i("--------------", "result : " + result); } } Log.i("-------------", "--------responseCode:---------" + conn.getResponseCode()); Log.i("-------------", "--------end---------"); } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) conn.disconnect(); } } }).start(); } }
最终效果图: