android网络编程之图片批量上传android客户端

//点击添加出现选择
private void showDialog() {
    View view = getLayoutInflater().inflate(R.layout.photo_choose_dialog,
            null);
    final Dialog dialog = new Dialog(this,
            R.style.transparentFrameWindowStyle);
    dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    Window window = dialog.getWindow();
    // 设置显示动画
    window.setWindowAnimations(R.style.main_menu_animstyle);
    WindowManager.LayoutParams wl = window.getAttributes();
    wl.x = 0;
    wl.y = getWindowManager().getDefaultDisplay().getHeight();
    // 以下这两句是为了保证按钮可以水平满屏
    wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
    wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

    // 设置显示位置
    dialog.onWindowAttributesChanged(wl);
    // 设置点击外围解散
    dialog.setCanceledOnTouchOutside(true);

    Button ablumBN = (Button) view.findViewById(R.id.pcd_btn_ablum);
    Button photoBN = (Button) view.findViewById(R.id.pcd_btn_take);
    Button cancelBN = (Button) view.findViewById(R.id.pcd_btn_cancel);

    ablumBN.setOnClickListener(new android.view.View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PicName = System.currentTimeMillis() + ".jpg";
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            intent.setDataAndType(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(intent, 0x12);
            dialog.dismiss();
        }
    });
    photoBN.setOnClickListener(new android.view.View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PicName = System.currentTimeMillis() + ".jpg";
            // 拍照意图
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File dir = new File(SavePicPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            startActivityForResult(intent, 0x11);
            dialog.dismiss();
        }
    });
    cancelBN.setOnClickListener(new android.view.View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    dialog.show();
}

//在onAcitvityResult中处理图片信息
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK && requestCode == 0x12) {
        Uri uri = data.getData();
        if (!TextUtils.isEmpty(uri.getAuthority())) {

            //选择查询照片
            Cursor cursor = getContentResolver().query(
                    uri, new String[]{MediaStore.Images.Media.DATA}, null, null, null);

            //返回 没有找到照片
            if (null == cursor) {
                return;
            }

            //光标移动至开头,获取图片路径
            cursor.moveToFirst();
            pathImage = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            cursor.close();
            Bitmap addmap = BitmapFactory.decodeFile(pathImage);

            File myCaptureFile = new File(SavePicPath, PicName);
            try {
                BufferedOutputStream bos = new BufferedOutputStream(
                        new FileOutputStream(myCaptureFile));
                addmap.compress(Bitmap.CompressFormat.JPEG, 10, bos);
                bos.flush();
                bos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    } else if (resultCode == RESULT_OK && requestCode == 0x11) {
        Uri uri = data.getData();
        if (uri == null) {
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                Bitmap photo = (Bitmap) bundle.get("data");
                try {
                    saveImage(photo, PicName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(getApplicationContext(), "err****", Toast.LENGTH_LONG).show();
                return;
            }
        }

    }
}


public void saveImage(Bitmap bm, String picName) throws IOException {
    File myCaptureFile = new File(SavePicPath, picName);
    BufferedOutputStream bos = new BufferedOutputStream(
            new FileOutputStream(myCaptureFile));
    bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
    bos.flush();
    bos.close();
}

//在返回activiy中onResume方法中刷新数据
@Override
protected void onResume() {
    super.onResume();
    if (!TextUtils.isEmpty(PicName)) {
        Bitmap addmap = BitmapFactory.decodeFile(SavePicPath + PicName);
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("itemImage", addmap);
        imageList.add(map);
        filesList.add(new File(SavePicPath + PicName));
        addPic();
    }

}

private void addPic() {
    simpleAdapter = new SimpleAdapter(this,
            imageList, R.layout.griditem_addpic,
            new String[]{"itemImage"}, new int[]{R.id.imageView1});

    simpleAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Object data,
                                    String textRepresentation) {
            // TODO Auto-generated method stub
            if (view instanceof ImageView && data instanceof Bitmap) {
                ImageView i = (ImageView) view;
                i.setImageBitmap((Bitmap) data);
                return true;
            }
            return false;
        }
    });
    gv.setAdapter(simpleAdapter);
    simpleAdapter.notifyDataSetChanged();
    //刷新后释放防止手机休眠后自动添加
    PicName = null;
}
// 到此为止图片添加到gridview已完成接下来只要上传就ok了


private void submit() {
    Button button = (Button) findViewById(R.id.sss);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    Map<String, Object> jsondata = new HashMap<String, Object>();
                    jsondata.put("content", "sssss");
                    HttpUtils httphandler = new HttpUtils(handler);
                    //这边是url的地址
                    HttpUtils.uploadFileToServer("/mobile/uploadComplaint", jsondata, filesList);
                }
            }).start();
        }
    });
}

//处理发送消息
Handler handler=new Handler(){
    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        switch (msg.what) {
            case HttpUtils.UPLOAD_SUCCESS:
                Toast.makeText(context, "上传成功", Toast.LENGTH_LONG).show();
                break;
            case HttpUtils.UPLOAD_FAIL:
                Toast.makeText(context, "上传失败", Toast.LENGTH_LONG).show();
                break;
            default:
                break;
        }
        super.handleMessage(msg);
    }
};

public class HttpUtils {

    public static final int UPLOAD_SUCCESS = 0x123;
    public static final int UPLOAD_FAIL = 0x124;
    private static Handler handler;

    public HttpUtils(Handler handler) {
        this.handler = handler;
    }
   
    public static String uploadFileToServer(final String command, final Map<String, Object> params, final ArrayList<File> files) {
        String result = null;

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (uploadFiles(command, params, files)) {
                        handler.sendEmptyMessage(UPLOAD_SUCCESS);//通知主线程发送成功
                    } else {
                        //发送失败
                        handler.sendEmptyMessage(UPLOAD_FAIL);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        return result;
    }

    private static boolean uploadFiles(String command, Map<String, Object> params, ArrayList<File> files) throws ClientProtocolException, IOException {
        //开启一个客户端请求
        HttpClient client = new DefaultHttpClient();
        //创建http post请求
        HttpPost post = new HttpPost(Constant.URL + command);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置流浪器兼容模式
        for (File file : files) {
            builder.addBinaryBody("files", file);
        }

        builder.addTextBody("content", String.valueOf(params.get("content")));//设置请求参数
        HttpEntity entity = builder.build();
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() == 200){
            return true;
        }
        return false;
    }

}


你可能感兴趣的:(android网络编程之图片批量上传android客户端)