客户端调用代码

86 阅读4分钟
<script type="text/javascript">
//初始化导入上传附件
$(function() { 
        var uploader=new plupload.Uploader({
        browse_button: "uploadFile", //DOM元素或者id
        url: ctx+"/landhouse/house!uploadFile4OCR.action?instanceId=${instanceId}&type=${type}&flag=${flag}",//请求路径   
        filters: {
            mime_types: [ //上传文件类型(数组)
                {
                    title: "file files", //过滤器名称
                    extensions: "pdf,xls,xlsx,doc,docx,txt,ppt,pptx,jpg,jpeg,bmp,gif,html,png" //文件扩展名,多个时用逗号隔开
                },
                {
                    title: "zip file",
                    extensions: "rar,zip"
                }
            ],
            max_file_size: "500mb", //上传文件大小(可以写b,kb,gb)
            prevent_duplicates: false //是否允许选取重复的文件
        },
        multipart: true, //是否使用multipart/form-data方式上传
        multipart_params: { //附加参数
            filePath: ""
        },
        max_retries: 0, //上传失败后的重试次数
        chunk_size: "10mb", //分片上传切割大小
        /* resize: {
            width: 100, //压缩图片宽度
            height: 100, //压缩图片高度
            crop: true,
            quality: 60, //压缩图片质量(默认90)
            preserve_headers: false
        }, */
        drop_element: "uploadFile", //拖拽上传区域DOM元素或者id(可以是数组)
        multi_selection: false, //是否支持多文件选择
        unique_names: true, //是否生成唯一name
        runtimes: "html5,flash,silverlight,html4", //支持的上传方式以及优先级
        file_data_name: "fileUpload", //文件域名称
//			        flash_swf_url: "${ctx}/js/plupload/Moxie.swf", //flash上传组件的url地址 
//			        silverlight_xap_url: "${ctx}/js/plupload/Moxie.xap", //silverlight上传组件的url地址
        init: { //监听函数
            FilesAdded: function(uploader,files) { //当文件添加到上传队列后触发
                uploader.start(); //开始上传
                $("body").showLoading();
                return false;
            },
            UploadProgress: function(uploader,uploadFile) { //会在文件上传过程中不断触发
                console.info(uploader.total.percent + "%");
                console.info(uploadFile.percent + "%"); //文件已上传部分所占的百分比
            },
            FileUploaded: function(uploader,uploadFile,responseObject) { //当队列中的某一个文件上传完成后触发
                console.info(responseObject.response); //服务器返回的文本
                var json = eval("("+responseObject.response+")");
                if(!json.success){
                        alert("图片解析失败")
                }
                if(json.success){
                        var url = '${ctx}/landhouse/house!findRightByRightIdFromOcr.action?houseVo.id=${ houseVo.id}&houseVo.houseCode=${ houseVo.houseCode}';
                                art.dialog.open(url, {title: '<!-- 土地证信息录入 --><l:w label="MOD_LANDHOUSE_86" language="${AuthenticateUserInfo.peopleLanguage }"/>', width: 1000, height: 500, lock: true});
                }
                console.info(responseObject.status); //服务器返回的http状态码,比如200
            },
            UploadComplete: function(uploader,uploadFile) { //当上传队列中所有文件都上传完成后触发
                $("body").hideLoading();			                

            },
            Error: function(uploader,errObject) { //当发生错误时触发
                console.info(errObject.code); //错误代码
                console.info(errObject.message); //错误信息
            }
        }
    }).init(); //初始化Plupload实例
});
</script>
ocr识别图片,客户端调用代码(基于jsp+Struts2)
/**
 * 房产证维护OCR附件上传(调用OCR接口识别图片)
 * @return
 * @throws Exception
 */
public String uploadFile4OCR() throws Exception {
try{
                String instanceId = request.getParameter("instanceId");
                String type = StringHelper.getValueFromRequestByName(request, "type");
                String flag = request.getParameter("flag");

                if(fileUploadFileName!=null && !"".equals(fileUploadFileName)){
                        //校验文件类型
                        boolean result = CommonUtils.checkSuffix(fileUploadFileName);
                        if(!result){
//					throw new Exception("文件名称可能包含特殊字符或文件名称超长");
//					String msg="false";
                                ajax("文件名称可能包含特殊字符或文件名称超长");
                        }else{
                                //首先发送请求给ocr系统,识别出图片对应的数据实体
                                rightOfHouseVo = houseService.distinguishPicture(fileUpload, fileUploadFileName, instanceId, type,flag);
                                //返回实体为空则待办解析失败,返回错误消息
                                if(rightOfHouseVo == null){
                                        this.ajaxResult("图片解析失败");
                                        return "";
                                }else{
                                        //解析成功,将接下来要用到的数据保存到session域中,并跳转到保存页面
                                        FileInputStream fis = new FileInputStream(fileUpload);
                                        byte[] buffer = new byte[fis.available()];
                                        fis.read(buffer);
                                        request.getSession().setAttribute("fis", fis);
                                        request.getSession().setAttribute("buffer", buffer);
                                        request.getSession().setAttribute("fileUploadFileName", fileUploadFileName);
                                        request.getSession().setAttribute("rightOfHouseVo", rightOfHouseVo);
                                        this.ajaxResult("");						
                                }
                        }
                }
}catch(Exception e){
        ajax(e.getMessage());
        return "";
}
return "";
}
 /*
 * 调用远程接口识别上传的附件,并返回数据
 */
public RightOfHouseVo distinguishPicture(File fileUpload,
                String fileUploadFileName, String instanceId, String type,
                String flag) {
        // TODO Auto-generated method stub
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SessionUserInfo userInfo = SessionUtil.getSessionUserInfo();
        LandHouseOcrResponse landHouseOcrResponse = null;
        RightOfHouseVo rightOfHouseVo = null;
        try {
                // 将图片转换为base64编码的类型,并生成请求实体
                FileInputStream inputFile = new FileInputStream(fileUpload);
                byte[] buffer = new byte[(int) fileUpload.length()];
                inputFile.read(buffer);
                inputFile.close();
                String base = new BASE64Encoder().encode(buffer);
                LandHouseOcrRequest landHouseRequest = new LandHouseOcrRequest();
                landHouseRequest.setImg(base);
                landHouseRequest.setFilecode(fileUploadFileName);
                landHouseRequest.setSource_type(1);
                //发送请求获得识别出来的数据
                landHouseOcrResponse = LandHouseOcrClient.getLandHouseOcr(
                                landHouseRequest, userInfo.getAccount());
                // 将识别的结果赋值到要展示的实体上
                rightOfHouseVo = new RightOfHouseVo();
                rightOfHouseVo.setRightCodeOfHouse(landHouseOcrResponse.getData().getCode());
                rightOfHouseVo.setHousePropertyee(landHouseOcrResponse.getData().getObligee());
                rightOfHouseVo.setHouseLocation(landHouseOcrResponse.getData().getAddress());
                rightOfHouseVo.setStructure(SysDictionaryUtil.getLabel("buildingStructure", landHouseOcrResponse.getData().getUsage()));
                if(landHouseOcrResponse.getData().getFloors() != null){
                        try{
                                rightOfHouseVo.setTotalFloor(Integer.parseInt(landHouseOcrResponse.getData().getFloors()));
                        }catch(Exception e){
                                rightOfHouseVo.setTotalFloor(null);
                        }

                }
                if(landHouseOcrResponse.getData().getArea() != null){
                        try{
                                rightOfHouseVo.setBuildingArea(Double.parseDouble(landHouseOcrResponse.getData().getArea()));
                        }catch(Exception e){
                                rightOfHouseVo.setBuildingArea(null);
                        }
                }			

        } catch (Exception e) {
                rightOfHouseVo = null;
                return rightOfHouseVo;
        }
        return rightOfHouseVo;
}
/**
 * 调用ocr识别系统识别图片接口
 * 
 * @param landHouseAkRequest
 * @param account
 * @return
 * @throws Exception
 */
public static LandHouseOcrResponse getLandHouseOcr(LandHouseOcrRequest landHouseOcrRequest, String account) throws Exception {

// 转换成字符串
        String json = JsonUtil.bean2json(landHouseOcrRequest);
System.out.println("---调用土地房屋OCR识别接口---" + json);
LandHouseOcrResponse landHouseOcrResponse = null;

// 调用接口URL
String url = SysPropertyUtil.getLandHouseOcrAddress();

        String appId = SysPropertyUtil.getLandHouseOcrAPPID(); // appId
        String appKey = SysPropertyUtil.getLandHouseOcrAPPKEY();// appKey

        String result = "";
        try {
                Map<String, String> headerMap = new HashMap<String, String>();
                headerMap.put("X-APP-ID", appId);
                headerMap.put("X-APP-KEY", appKey);
                result = HttpClientUtil.doHttpPost(json, url, headerMap);
                System.out.println(result);

                // 转换成接口处理类
                landHouseOcrResponse = JsonUtil.json2Bean(result, LandHouseOcrResponse.class);
                return landHouseOcrResponse;
        } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("接口异常:"+e.getMessage());
        } finally {
                // 记录日志
                LogUtil.doAsynRecordLog(LandHouseOcrClient.class.getName(), "LandHouseOcr",
                                json, result, ConfigUtil.SERVER_ADDRESS, account);
        }
}
/**
 * 序列化对象为JSON格式 遵循JSON组织公布标准
 * 
 * @date 2008/05/07
 * @version 1.0.0
 */
public class JsonUtil {
	
	public static final String FORMAT_1 = "yyyy-MM-dd";
	public static final String FORMAT_2 = "yyyy/MM/dd";
	
    /**
     * @param obj
     *            任意对象
     * @return String
     */
    public static String object2json(Object obj) {
        StringBuilder json = new StringBuilder();
        if (obj == null) {
            json.append("\"\"");
        }
        else if (obj instanceof String || obj instanceof Integer || obj instanceof Float
                || obj instanceof Boolean || obj instanceof Short || obj instanceof Double
                || obj instanceof Long || obj instanceof BigDecimal || obj instanceof BigInteger
                || obj instanceof Byte) {
            json.append("\"").append(string2json(obj.toString())).append("\"");
        }
        else if (obj instanceof Date) {
            (new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).format(obj);
            json.append("\"").append(string2json(obj.toString())).append("\"");
        }

        else if (obj instanceof Object[]) {
            json.append(array2json((Object[]) obj));
        }
        else if (obj instanceof List) {
            json.append(list2json((List<?>) obj));
        }
        else if (obj instanceof Map) {
            json.append(map2json((Map<?, ?>) obj));
        }
        else if (obj instanceof Set) {
            json.append(set2json((Set<?>) obj));
        }
        else {
            json.append(bean2json(obj));
        }

        return json.toString();
    }

    /**
     * @param bean
     *            bean对象
     * @return String
     */
    public static String bean2json(Object bean) {
        StringBuilder json = new StringBuilder();
        json.append("{");
        PropertyDescriptor[] props = null;
        try {
            props = Introspector.getBeanInfo(bean.getClass(), Object.class)
                    .getPropertyDescriptors();
        } catch (IntrospectionException e) {
        }
        if (props != null) {
            for (int i = 0; i < props.length; i++) {
                try {
                    String name = object2json(props[i].getName());
                    String value = object2json(props[i].getReadMethod().invoke(bean));
                    json.append(name);
                    json.append(":");
                    json.append(value);
                    json.append(",");
                } catch (Exception e) {
                }
            }
            json.setCharAt(json.length() - 1, '}');
        }
        else {
            json.append("}");
        }
        return json.toString();
    }

    /**
     * @param list
     *            list对象
     * @return String
     */
    public static String list2json(List<?> list) {
        StringBuilder json = new StringBuilder();
        json.append("{ \"results\": " + list.size() + ", \"rows\": ");
        json.append("[");
        if (list != null && list.size() > 0) {
            for (Object obj : list) {
                json.append(object2json(obj));
                json.append(",");
            }
            json.setCharAt(json.length() - 1, ']');
        }
        else {
            json.append("]");
        }
        json.append("}");
        return json.toString();
    }

    /**
     * @param array
     *            对象数组
     * @return String
     */
    public static String array2json(Object[] array) {
        StringBuilder json = new StringBuilder();
        json.append("[");
        if (array != null && array.length > 0) {
            for (Object obj : array) {
                json.append(object2json(obj));
                json.append(",");
            }
            json.setCharAt(json.length() - 1, ']');
        }
        else {
            json.append("]");
        }
        return json.toString();
    }

    /**
     * @param map
     *            map对象
     * @return String
     */
    public static String map2json(Map<?, ?> map) {
        StringBuilder json = new StringBuilder();
        json.append("{");
        if (map != null && map.size() > 0) {
            for (Object key : map.keySet()) {
                json.append(object2json(key));
                json.append(":");
                json.append(object2json(map.get(key)));
                json.append(",");
            }
            json.setCharAt(json.length() - 1, '}');
        }
        else {
            json.append("}");
        }
        return json.toString();
    }

    /**
     * @param set
     *            集合对象
     * @return String
     */
    public static String set2json(Set<?> set) {
        StringBuilder json = new StringBuilder();
        json.append("[");
        if (set != null && set.size() > 0) {
            for (Object obj : set) {
                json.append(object2json(obj));
                json.append(",");
            }
            json.setCharAt(json.length() - 1, ']');
        }
        else {
            json.append("]");
        }
        return json.toString();
    }

    /**
     * @param s
     *            参数
     * @return String
     */
    public static String string2json(String s) {
        if (s == null)
            return "";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            switch (ch) {
            case '"':
                sb.append("\\\"");
                break;
            case '\\':
                sb.append("\\\\");
                break;
            case '\b':
                sb.append("\\b");
                break;
            case '\f':
                sb.append("\\f");
                break;
            case '\n':
                sb.append("\\n");
                break;
            case '\r':
                sb.append("\\r");
                break;
            case '\t':
                sb.append("\\t");
                break;
            case '/':
                sb.append("\\/");
                break;
            default:
                if (ch >= '\u0000' && ch <= '\u001F') {
                    String ss = Integer.toHexString(ch);
                    sb.append("\\u");
                    for (int k = 0; k < 4 - ss.length(); k++) {
                        sb.append('0');
                    }
                    sb.append(ss.toUpperCase());
                }
                else {
                    sb.append(ch);
                }
            }
        }
        return sb.toString();
    }

    /**
     * @param obj
     *            要转化的对象
     * @param map<"0","fieldName1"> map<"1","fieldName2">
     *            需要转化的字段 如果为空,则是全部的字段
     * @return
     * @throws Exception
     */
    public static String beanToJson(Object obj, Map<String, String> map) throws Exception {
        JSONArray jsonArray = new JSONArray();
        JSONObject bean = new JSONObject();
        
        Class<?> clazz = obj.getClass();   
        Method[] methods = clazz.getMethods();
        Field fields[] = clazz.getDeclaredFields();
        
        for(Field field:fields){ 
            if(map==null){
                String fieldName = field.getName();
                String getMetName = ReflectUtil.pareGetName(field.getName()); 
                if(!ReflectUtil.checkMethod(methods,getMetName)){  
                    continue;  
                } 
                Class<?>[] parameterTypes =null;
                Method method = clazz.getMethod(getMetName, parameterTypes);  
                Object object = method.invoke(obj, new Object[]{});
                if(object == null){
                    object = new String("");
                }
                bean.element(fieldName,object);                
            }else {
                String fieldName = field.getName();
                if (map.containsValue(fieldName)) {
                    String getMetName = ReflectUtil.pareGetName(field.getName()); 
                    if(!ReflectUtil.checkMethod(methods,getMetName)){  
                        continue;  
                    } 
                    Class<?>[] parameterTypes =null;
                    Method method = clazz.getMethod(getMetName, parameterTypes);  
                    Object object = method.invoke(obj, new Object[]{});
                    if(object == null){
                        object = new String("");
                    }
                    bean.element(fieldName,object);
                }            
            }
        }   
        jsonArray.add(map);
        jsonArray.add(bean);
        return jsonArray.toString();
    }
    
    /**
     * 将字符串转成对象
     * 
     * @param json json字符串
     * @param cla 转换成BEAN对应的CLASS
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T json2Bean(String json, Class<T> cla) {
        JSONObject jsonObject = JSONObject.fromObject(json);
        return (T) JSONObject.toBean(jsonObject, cla);
    }
    
    /**
     * 将字符串转成对象list
     * 
     * @param <E>
     * @param jsonStr
     * @param cla
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <E> List<E> json2List(String jsonStr, Class<E> cla) {
        List<E> itemList = new ArrayList<E>();
        JSONArray jsonarray = JSONArray.fromObject(jsonStr);
        for (int i = 0; i < jsonarray.size(); i++) {
        	
            JSONObject object = jsonarray.getJSONObject(i);
            //注册时间类型
            String[] formats = new String[] {"yyyy-MM-dd HH:mm:ss","yyyy/MM/dd HH:mm:ss","yyyy-MM-dd","yyyy/MM/dd"}; 
    		JSONUtils.getMorpherRegistry().registerMorpher(new TimestampMorpher(formats));
            JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(formats)); 
    		
            E item = (E)JSONObject.toBean(object, cla);
            itemList.add(item);
        }
        
        return itemList;
    }
    
    @SuppressWarnings("unchecked")
    public static <E> List<E> json2List(String jsonStr, Class<E> cla,List<ColumnData> columnDatas,List<String>  failsList) {
        List<E> itemList = new ArrayList<E>();
        JSONArray jsonarray = JSONArray.fromObject(jsonStr);
        for (int i = 0; i < jsonarray.size(); i++) {
        	
            JSONObject object = jsonarray.getJSONObject(i);
            //注册时间类型
            String[] formats = new String[] {"yyyy-MM-dd HH:mm:ss","yyyy/MM/dd HH:mm:ss","yyyy-MM-dd","yyyy/MM/dd"}; 
    		JSONUtils.getMorpherRegistry().registerMorpher(new TimestampMorpher(formats));
            JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(formats)); 
    		
            E item = (E)JSONObject.toBean(object, cla);
            checkJson2ListFailProperty(object,item,columnDatas,failsList);
            itemList.add(item);
        }
        
        return itemList;
    }
    
    /**
     * 校验JSONObject与E中均存在的属性,并且当JSONObject有值但E中没转化成对应的值,记录在错误列表failsList中
     *     e.g.     日期  “2018-02-30” 转化成对应的DATE值时为空的情况 
     * @param object json对象
     * @param entry  实体对象
     * @param columnDatas导入对应的字段说明信息
     * @param failsList 转化失败提示信息
     * @throws IllegalAccessException 
     * @throws IllegalArgumentException 
     */
    public static <E>  void checkJson2ListFailProperty(JSONObject object,  E   entry,List<ColumnData> columnDatas,List<String>  failsList){
    	 
    	Field[] fieldArray =   entry.getClass().getDeclaredFields();
    	for(int i=0;i<fieldArray.length;i++) {
    		//首先判断E中是否存在该属性
    		fieldArray[i].setAccessible(true);
    		String propertyName = fieldArray[i].getName();
    		if(object.containsKey(propertyName)){
    			ColumnData  columnData = findColumnDataByName(columnDatas,propertyName); 
    			try{
	    			if(!StringHelper.isEmpty(object.get(propertyName)) && fieldArray[i].get(entry)==null ){
	    				System.out.println("1:"+propertyName+"---"+object.get(propertyName).toString()+"---");
	    				String hint =columnData==null?"值:"+object.get(propertyName)+"无效,无法转化;":columnData.getColumnTitle()+"值:"+object.get(propertyName)+"无效,无法转化;";
	    				failsList.add(hint);
	    			}
    			}catch(Exception e){
    				e.printStackTrace();
    				failsList.add(e.getMessage());
    			}
    		}
	    }
        
    		  
    }
    
    /**
     * 根据字段名称找对应的导入列结构信息
     * @param columnDatas
     * @param fieldName
     * @return
     */
    public static ColumnData findColumnDataByName(List<ColumnData> columnDatas,String fieldName){
    	ColumnData result=null;
    	for(ColumnData columnData:columnDatas){
    		//如果找到对应的字段
    		if(columnData.getColumnValue().equals(fieldName)){
    			result=columnData;
    			break;
    		}
    	}
    	return result;
    }
    
    public static JSONArray toJsonArr(Object obj){
        JsonConfig jsonConfig=new JsonConfig();
        jsonConfig.registerJsonValueProcessor(ArrayList.class,new JsonDefaultValueProcessor());
        
        return JSONArray.fromObject(obj, jsonConfig);
    }
    //对于反向应用的实体,则需要传入class,假如需要显示那些属性,可以配置在propertys
    public static JSONArray toJsonArr(Object obj,Class clz,String[] propertys){
    	
        JsonConfig jsonConfig=new JsonConfig();
        jsonConfig.registerJsonValueProcessor(ArrayList.class,new JsonDefaultValueProcessor());
        jsonConfig.registerJsonValueProcessor(clz, 
        	       new ObjectJsonValueProcessor(propertys,clz));
        
        return JSONArray.fromObject(obj, jsonConfig);
    }
    
    public static JSONObject toJsonObject(Object obj){
    	
    	JsonConfig jsonConfig = new JsonConfig();
    	//@1:注册时间类型为自定义类型JsonDateValueProcessor
		JsonValueProcessor dateValueProcessor = new JsonDefaultValueProcessor();
		
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, dateValueProcessor);
		jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class, dateValueProcessor);
		
        return JSONObject.fromObject(obj, jsonConfig);
    }

	public static Map<String, Object> parseJSON2Map(String jsonStr) {
		Map<String, Object> map = new HashMap<String, Object>();
		// 最外层解析
		JSONObject json = JSONObject.fromObject(jsonStr);
		for (Object k : json.keySet()) {
			Object v = json.get(k);
			// 如果内层还是数组的话,继续解析
			if (v instanceof JSONArray) {
				List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
				Iterator<JSONObject> it = ((JSONArray) v).iterator();
				while (it.hasNext()) {
					JSONObject json2 = it.next();
					list.add(parseJSON2Map(json2.toString()));
				}
				map.put(k.toString(), list);
			} else {
				map.put(k.toString(), v);
			}
		}
		return map;
		
	}
	/**
	 * JSON转List集合
	 * 
	 * @param jsonStr
	 * @return
	 */
	public static List<Map<String, Object>> parseJSON2List(String jsonStr) {
		JSONArray jsonArr = JSONArray.fromObject(jsonStr);
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Iterator<JSONObject> it = jsonArr.iterator();
		while (it.hasNext()) {
			JSONObject json2 = it.next();
			list.add(parseJSON2Map(json2.toString()));
		}
		return list;
	}
    
}