<script type="text/javascript">
$(function() {
var uploader=new plupload.Uploader({
browse_button: "uploadFile",
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",
prevent_duplicates: false
},
multipart: true,
multipart_params: {
filePath: ""
},
max_retries: 0,
chunk_size: "10mb",
drop_element: "uploadFile",
multi_selection: false,
unique_names: true,
runtimes: "html5,flash,silverlight,html4",
file_data_name: "fileUpload",
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);
},
UploadComplete: function(uploader,uploadFile) {
$("body").hideLoading();
},
Error: function(uploader,errObject) {
console.info(errObject.code);
console.info(errObject.message);
}
}
}).init();
});
</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) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
SessionUserInfo userInfo = SessionUtil.getSessionUserInfo();
LandHouseOcrResponse landHouseOcrResponse = null;
RightOfHouseVo rightOfHouseVo = null;
try {
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()
String appKey = SysPropertyUtil.getLandHouseOcrAPPKEY()
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
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
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
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
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
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
//首先判断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
}
}