拍照上传

//上传代码,第一个参数,为要使用的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;      } 
相关文章
相关标签/搜索