Android批量文件上传

在百度完所有的的批量上传文件或图片无果之后。要么写的太渣、要么写的太乱,反正没让我看懂,最终决定进下心来自己写........

有这么一个需求,“我要上传姓名、身份证号、机构代码、身份证照片、营业执照、组织机构图”

其实很简单用MultipartEntity类就可以完成数据的传送, 我最开始用的是NameValuePair这个类,这个类只能存以String为键值的类型,接着我就走入误区,把文件各种转换,但是最终无果。

代码如下:

    public void certification(String name, String idCode, String code) {//参数1:姓名 参数2:身份证 参数3:机构代码
        HttpClient httpclient = new DefaultHttpClient();
        //设置通信协议版本
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        /*建立HTTP Post联机*/
        HttpPost httpRequest = new HttpPost(PublicVariable.putMateria);//参数为服务器的url
        // Post运作传送数据用
        MultipartEntity mpEntity = new MultipartEntity();
        try {
            mpEntity.addPart("name", new StringBody(name));//StringBody将name转成字符串
            mpEntity.addPart("identification", new StringBody(idCode));
            mpEntity.addPart("org_code", new StringBody(code));
	    //mFileList是3张图片的文件路径 List<File> mFileList;
            for (int i = 0; i < mFileList.size(); i++) {
                File file = mFileList.get(i);
                mpEntity.addPart("file", new FileBody(file));//主要就是它,转换成文件
                Log.e("akui", "3张图片文件 == " + file);
            }
        } catch (UnsupportedEncodingException ignored) {
        }
        try {
            /*发出HTTP request*/
            httpRequest.setEntity(mpEntity);
            /*取得HTTP response*/
            HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
            /*若状态码为200 ok*/
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                /*取出响应字符串*/
                String strResult = EntityUtils.toString(httpResponse.getEntity());
                Log.e("------->", "响应结果:true");
                Log.e("------->", "响应结果:" + strResult);
                JSONObject json = new JSONObject(strResult);
                int result = json.getInt("result");
                Log.e("------->", "result == " + result);
                if (result == 0) {
                    sendHintMessage("数据上传成功", true);
                } else {
                    String erro = json.getString("msg");
                    sendHintMessage(erro, false);
                }
                Log.e("------->", "msg:" + json.toString());
            } else {
                Log.e("------->", "响应结果:false");
            }
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        } catch (Exception e) {
        }
    }


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值