獲取許可權 頁面佈局視圖: 效果是:點擊圖片1:拍照上傳,1張或多張。 點擊圖片2:從相冊中選擇照片上傳 Activity核心代碼: 最終效果圖: ...
獲取許可權
<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(); } }
最終效果圖: