//上傳代碼,第一個參數,爲要使用的URL,第二個參數,爲表單內容,第三個參數爲要上傳的文件,能夠上傳多個文件,這根據須要頁定
private static final String TAG = "uploadFile";
private static final int TIME_OUT = 10*1000; //超時時間
private static final String CHARSET = "utf-8"; //設置編碼
/**
* android上傳文件到服務器
* @param file 須要上傳的文件
* @param RequestURL 請求的rul
*
@return 返回響應的內容 */ public static String uploadFile(File file,String RequestURL) { String result = null; 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) { /** * 當文件不爲空,把文件包裝而且上傳 */ DataOutputStream dos = new DataOutputStream( conn.getOutputStream()); 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=\"fup\"; filename=\""+file.getName()+"\""+LINE_END); sb.append("Content-Type: image/pjpeg; charset="+CHARSET+LINE_END); sb.append(LINE_END); 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(); Log.i(TAG, "response code:"+res); if(res==200) { Log.e(TAG, "request success"); InputStream input = conn.getInputStream(); StringBuffer sb1= new StringBuffer(); int ss ; while((ss=input.read())!=-1) { sb1.append((char)ss); } result = sb1.toString(); Log.i(TAG, "result : "+ result); } else{ Log.i(TAG, "request error"); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } 這個方法須要傳遞一個由圖片的path(路徑)生成的file格式的數據。和上傳地址的url。 首先是本地上傳。 [java] view plaincopy /*** * 這個是調用android內置的intent,來過濾圖片文件 ,同時也能夠過濾其餘的 */ Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, selectCode); 這個是調用本地圖片庫。 返回事後是在 ResultActivty裏返回。 [java] view plaincopy protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(selectCode==requestCode){ /** * 當選擇的圖片不爲空的話,在獲取到圖片的途徑 */ Uri uri = data.getData(); Log.i(TAG, "uri = "+ uri); 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")) { picPath = path; Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri)); imageView.setImageBitmap(bitmap); }else{alert();} }else{alert();} } catch (Exception e) { } super.onActivityResult(requestCode, resultCode, data); } 取值,而且將圖片填充到imageView裏。本Activty裏全局變量保存picPath。 拍照上傳,首先要進入照相機。 [java] view plaincopy destoryBimap(); String state = Environment.getExternalStorageState(); if (state.equals(Environment.MEDIA_MOUNTED)) { intent = new Intent("android.media.action.IMAGE_CAPTURE"); startActivityForResult(intent, cameraCode); } else { Toast.makeText(SsActivity.this,"請插入SD卡", Toast.LENGTH_LONG).show(); } break; 判斷有沒有SD卡。沒有就提示插入SD卡。接受返回值任然實在ResultActivity [java] view plaincopy if(cameraCode==requestCode){ Bundle bundle = data.getExtras(); photo= (Bitmap) bundle.get("data");// 獲取相機返回的數據,並轉換爲Bitmap圖片格式 ByteArrayOutputStream baos = new ByteArrayOutputStream(); photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 把數據寫入文件 Uri uri = data.getData(); Log.i(TAG, "uri = "+ uri); try { String[] pojo = {MediaStore.Images.Media.DATA}; Cursor cursor = managedQuery(uri, pojo, null, null,null); if(cursor!=null){ int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String path = cursor.getString(colunm_index); if(path!=null){ picPath=path; imageView.setImageBitmap(photo); } } }catch (Exception e) { // TODO: handle exception } } 此返回值跟上面本地取圖片同樣。返回picPath,而且將圖片填充至imageView。 上傳: [java] view plaincopy File file = new File(saveBefore(picPath)); if(file!=null) { String request = PostFile.uploadFile( file, requestURL); uploadImage.setText(request); } break; 上傳以前將圖片壓縮。 如今附上一些轉換方法 [java] view plaincopy private void destoryBimap() { if (photo != null && !photo.isRecycled()) { photo.recycle(); photo = null; } } [java] view plaincopy /** * 讀取路徑中的圖片,而後將其轉化爲縮放後的bitmap * @param path */ public String saveBefore(String path) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; // 獲取這個圖片的寬和高 Bitmap bitmap = BitmapFactory.decodeFile(path, options); // 此時返回bm爲空 options.inJustDecodeBounds = false; // 計算縮放比 int be = (int) (options.outHeight / (float) 200); if (be <= 0) be = 1; options.inSampleSize = 4; // 圖片長寬各縮小至四分之一 // 從新讀入圖片,注意此次要把options.inJustDecodeBounds 設爲 false哦 bitmap = BitmapFactory.decodeFile(path, options); // savePNG_After(bitmap,path); return saveJPGE_After(bitmap, path); } /** * 保存圖片爲JPEG * @param bitmap * @param path */ public String saveJPGE_After(Bitmap bitmap, String path) { File file = new File(path); try { FileOutputStream out = new FileOutputStream(file); if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) { out.flush(); out.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return path; }