1.案例场景
此处,我这里需要前端实现上传身份证OCR识别证件号码。
2.前端实现方式
2.1页面按钮
<div class="title-icon"></div>身份证正面信息
<a href="javascript:void(0)" id="uploadIdcardZmBtn">
<font style="color: #999999;float:right;">(请点击拍照识别)</font>
<img id="idcardZm" alt="" src="../img/idCard_zm_eg.png" style="transform:scale(0.7);"/>
</a>
<input type="file" name="idcardZmFile" id="idcardZmFile" title="" style="display:none;" onchange="uploadFile('face')">
</h1>
2.2页面JS实现
首先页面初始化先给隐藏input 类型为file的上传按钮绑定事件,并且增加上传按钮的change事件函数。
注:此处我的projectName="/jjxt"
具体对应后台application.yml 文件中
如果前端请求后台是通过nginx访问,我这里通过nginx反向代理也是为了解决前端ajax请求跨域的问题,那这里projectName 对应nginx.conf中配置的server路径:
此处,附上nginx反向代理的代码,具体可根据自身需求修改配置项
server {
listen 8088;
server_name localhost;
#add_header Access-Control-Allow-Origin *; #表示服务器可以接受所有跨域请求
#add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
#add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
location / {
#root路劲配置页面首页的访问路径前缀,根据自己项目路径做出修改
root E:/xxx/xxx/src/main/webapps/jjhtml;
index index.html index.htm;
}
location /jjxt {
proxy_send_timeout 600;
proxy_read_timeout 600;
proxy_connect_timeout 600;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://localhost:8801/jjxt;
add_header Access-Control-Allow-Origin *;
}
}
注:此处用到了ajax文件上传的js工具类ajaxfileupload.js
文件内容如下:
jQuery.extend({
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error ) {
s.error.call( s.context || s, xhr, status, e );
}
// Fire the global callback
if ( s.global ) {
(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
}
},
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
if(window.ActiveXObject) {
var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
if(typeof uri== 'boolean'){
io.src = 'javascript:false';
}
else if(typeof uri== 'string'){
io.src = uri;
}
}
else {
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px';
document.body.appendChild(io);
return io
},
createUploadForm: function(id, fileElementId)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
var oldElement = $('#' + fileElementId);
var newElement = $(oldElement).clone();
$(oldElement).attr('id', fileId);
$(oldElement).before(newElement);
$(oldElement).appendTo(form);
//set attributes
$(form).css('position', 'absolute');
$(form).css('top', '-1200px');
$(form).css('left', '-1200px');
$(form).appendTo('body');
return form;
},
addOtherRequestsToForm: function(form,data)
{
// add extra parameter
var originalElement = $('<input type="hidden" name="" value="">');
for (var key in data) {
name = key;
value = data[key];
var cloneElement = originalElement.clone();
cloneElement.attr({'name':name,'value':value});
$(cloneElement).appendTo(form);
}
return form;
},
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId);
if ( s.data ) form = jQuery.addOtherRequestsToForm(form,s.data);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function()
{ try
{
$(io).remove();
$(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
// var io = $('#' + frameId);
var form = $('#' + formId);
$(form).attr('action', s.url);
$(form).attr('method', 'POST');
$(form).attr('target', frameId);
if(form.encoding)
{
form.encoding = 'multipart/form-data';
}
else
{
form.enctype = 'multipart/form-data';
}
$(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if(window.attachEvent){
document.getElementById(frameId).attachEvent('onload', uploadCallback);
}
else{
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
}
return {abort: function () {}};
},
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
{
// If you add mimetype in your response,
// you have to delete the '<pre></pre>' tag.
// The pre tag in Chrome has attribute, so have to use regex to remove
var data = r.responseText;
var rx = new RegExp("<pre.*?>(.*?)</pre>","i");
var am = rx.exec(data);
//this is the desired data extracted
var data = (am) ? am[1] : ""; //the only submatch or empty
eval( "data = " + data );
}
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
//alert($('param', data).each(function(){alert($(this).attr('value'));}));
return data;
}
})
//请求服务器的项目路径对应后台设置的context-path的值
var projectName="/jjxt";
function httpsOrhttp(){
var protocolStr = document.location.protocol;
if(protocolStr == "http:") return "http://";
else if(protocolStr == "https:")return "https://";
}
var ip = httpsOrhttp()+location.hostname+":"+location.port; //获取本地服务器
$(function(){
//上传按钮绑定事件
$("#uploadIdcardZmBtn").click(function(){
$("[name='idcardZmFile']").click();
});
});
//上传方法,内部逻辑根据自身需求做出相应修改
function uploadFile(side){
var nsrsbh = StorageInfo.getNsrsbh();
var value = "";
var fileId="";
//这里我是上传身份证正反面共用一个方法,所以上传文件的id标识做了一个区分判断
if(side=="face"){
fileId="idcardZmFile";
value=$("#idcardZmFile").val();
}else{
fileId="idcardFmFile";
value=$("#idcardFmFile").val();
}
if(value==null||value==""){
Prompt.alert("请拍照上传身份证!");
return false;
}
var fileType = value.slice(value.lastIndexOf(".")+1).toLowerCase();
if ("png" != fileType && "jpg" != fileType && "jpeg"!=fileType) {
Prompt.alert("只能上传jpg、jpeg、png文件");
$("#idcardZmFile").val("");
$("#idcardFmFile").val("");
return false;
}
//这里是请求前的遮罩,修改为自己项目的方法
$(".Z_loading").show();
$.ajaxFileUpload({
url:ip + projectName+'/uploadIdcardFile?nsrsbh='+nsrsbh+'&side='+side+'&fileType='+fileType,
secureuri:false,
fileElementId:fileId, //文件选择框的id属性
dataType: 'text', //服务器返回的格式
success: function (data){
$(".Z_loading").hide();
$("#licenseFile").val("");
data = $.parseJSON(data.replace(/<.*?>/ig,""));
if(data.state=="0"){
var retData=JSON.parse(data.result);
//src此处是回显上传后的页面图片,文件流方式回显,这里手机端不建议跟作者这样的操作
var src = "data:image/"+fileType+";base64,"+retData.cardFile.replace(/[\r\n]/g, '');
if(side=="face"){
$("#idcardZm").css("width", "90%");
$("#idcardZm").css("height", "30%");
$("#idcardZm").attr("src",src);
$("#idcardName").val(retData.idcardName);
$("#skr_zjhm").val(retData.skr_zjhm);
}else{//back
$("#idcardFm").css("width", "90%");
$("#idcardFm").css("height", "30%");
$("#idcardFm").attr("src",src);
$("#issue").val(retData.issue);
$("#qfrq").val(retData.qfrq);
$("#yxq").val(retData.yxq);
}
}else{
Prompt.alert(data.message);
}
},
error: function (){
$(".Z_loading").hide();
Prompt.alert('上传身份证失败!');
}
});
}
3.后端Java接收上传文件Controller的代码示例如下:
@RequestMapping(value = "/uploadIdcardFile", method = RequestMethod.POST)
@ResponseBody
public ResData uploadIdcardFile(String nsrsbh, HttpServletRequest request,HttpServletResponse response) throws Exception {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
String side = request.getParameter("side");//证件正面或反面标识
String fileType = request.getParameter("fileType");
String fileId="";
if(OcrIdcard.sideFace.equals(side)) {
fileId="idcardZmFile";
}else {
fileId="idcardFmFile";
}
MultipartFile file =multipartRequest.getFile(fileId);
log.info("1.开始上传身份证照片,nsrsbh={},side={}。。。。。。。。。。。。。。。。",nsrsbh,side);
if(StringUtil.isEmpty(file) || file.getSize()==0) {
logger.error("身份证照片为空!");
return new ResData(ResponseEnum.REQPARAMS_ERROR.getState(), null, "身份证照片为空!");
}
JSONObject result=new JSONObject();
try {
//此处开始为具体的业务逻辑处理
JjSkrIdcard entity=new JjSkrIdcard();
entity.setNsrsbh(nsrsbh);
//这里我是数据库存储图片为longblob类型,所以转二进制的
String imgBase64 = Base64Util.encode(IOUtils.toByteArray(file.getInputStream()));
ResData ocrIdCard = OcrIdcard.ocrIdCard(side, imgBase64);
if(!ResponseEnum.SUCCESS.getState().equals(ocrIdCard.getState())) {
log.info("2.结束并OCR身份证识别异常,nsrsbh={},side={},异常信息={}。。。。。。。。。。。。。。。。",nsrsbh,side,ocrIdCard.getMessage());
return new ResData(ResponseEnum.FAIL.getState(), null, ocrIdCard.getMessage());
}else {
JSONObject parseObject = JSON.parseObject(ocrIdCard.getResult());
if(!parseObject.getBooleanValue("success")) {
return new ResData(ResponseEnum.FAIL.getState(), null, "OCR识别身份证失败!");
}
if(OcrIdcard.sideFace.equals(side)) {
entity.setSkrIdcardZm(imgBase64);
entity.setSkrIdcardZmType(fileType);
entity.setIdcardName(parseObject.getString("name"));
entity.setIdcardZjhm(parseObject.getString("num"));
entity.setAddress(parseObject.getString("address"));
entity.setSex(parseObject.getString("sex"));
entity.setBirth(parseObject.getString("birth"));
entity.setNationality(parseObject.getString("nationality"));
result.put("skr_zjhm", entity.getIdcardZjhm());
result.put("idcardName", entity.getIdcardName());
}else {
entity.setSkrIdcardFm(imgBase64);
entity.setSkrIdcardFmType(fileType);
entity.setIssue(parseObject.getString("issue"));
entity.setQfrq(parseObject.getString("start_date"));
entity.setYxq(parseObject.getString("end_date"));
result.put("issue", entity.getIssue());
result.put("qfrq", entity.getQfrq());
result.put("yxq", entity.getYxq());
}
}
QueryWrapper<JjSkrIdcard> queryWrapper =new QueryWrapper<JjSkrIdcard>();
queryWrapper.eq("nsrsbh", nsrsbh);
JjSkrIdcard one = JjSkrIdcardService.getOne(queryWrapper);
if(one==null) {
entity.setId(SnowFlake.getid());
entity.setCreateTime(new Date());
JjSkrIdcardService.save(entity);
}else {
entity.setId(one.getId());
entity.setUpdateTime(new Date());
JjSkrIdcardService.updateById(entity);
}
result.put("cardFile",imgBase64);
} catch (Exception e) {
log.info("2.结束并保存身份证照片异常,nsrsbh={},side={}。。。。。。。。。。。。。。。。",nsrsbh,side);
return new ResData(ResponseEnum.FAIL.getState(), null, "保存身份证照片异常!");
}
log.info("2.结束并成功上传身份证照片,nsrsbh={},side={}。。。。。。。。。。。。。。。。",nsrsbh,side);
return new ResData(ResponseEnum.SUCCESS.getState(), result.toJSONString(), ResponseEnum.SUCCESS.getStateInfo());
}
ps:设置文件上传限制大小
https://blog.csdn.net/weixin_36754290/article/details/124827767