ps:有很长一段时间没有上博客了。将源码贴出。
在网上看到的案例纯属扯淡。还不如自己写。
转载请注明地址谢谢。
首先是上传的 PostFile
-
- private static final String TAG = "uploadFile";
- private static final int TIME_OUT = 10*1000;
- private static final String CHARSET = "utf-8";
-
-
-
-
-
-
- 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);
-
-
-
-
-
- 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();
-
-
-
-
- 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。
首先是本地上传。
-
-
-
- Intent intent = new Intent();
- intent.setType("image/*");
- intent.setAction(Intent.ACTION_GET_CONTENT);
- startActivityForResult(intent, selectCode);
这个是调用本地图片库。
返回过后是在 ResultActivty里返回。
- 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。
拍照上传,首先要进入照相机。
- 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
- if(cameraCode==requestCode){
- Bundle bundle = data.getExtras();
- photo= (Bitmap) bundle.get("data");
- 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) {
-
- }
- }
此返回值跟上面本地取图片一样。返回picPath,并且将图片填充至imageView。
上传:
- File file = new File(saveBefore(picPath));
- if(file!=null)
- {
- String request = PostFile.uploadFile( file, requestURL);
- uploadImage.setText(request);
- }
- break;
上传之前将图片压缩。
现在附上一些转换方法
- private void destoryBimap() {
- if (photo != null && !photo.isRecycled()) {
- photo.recycle();
- photo = null;
- }
- }
-
-
-
-
- public String saveBefore(String path) {
- BitmapFactory.Options options = new BitmapFactory.Options();
- options.inJustDecodeBounds = true;
-
- Bitmap bitmap = BitmapFactory.decodeFile(path, options);
- options.inJustDecodeBounds = false;
-
- int be = (int) (options.outHeight / (float) 200);
- if (be <= 0)
- be = 1;
- options.inSampleSize = 4;
-
- bitmap = BitmapFactory.decodeFile(path, options);
-
- return saveJPGE_After(bitmap, 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;
- }