SSH框架不用form表单上传图片两种方式FormData和ajaxFileUpload

两种方式FormData最好用简单ajaxFileUpload有bug,会出现 第二个文件上传图片onchange无效问题

我是以百度身份证识别为例。

ajaxFileUpload

ajaxFileUpload要先引入ajaxFileUpload.js-->下载

jsp页面

<script type="text/javascript">
function selectFile(id) {
	$("#"+id).click();
};
function changecard(typeOcr) {
    //企业法人身份证
    //alert(2);
    //var idcard ='idcard';
    alert(typeOcr);
    $.ajaxFileUpload({  
        async: false,  
        cache:false,  
        type: 'POST',
        dataType : "json",
        fileElementId : 'upload', 
        //data: {filetype: "business_license"},
        url: '<%=basePath%>'+"get/creditinfo_baiduOcr.action?filetype="+typeOcr,//请求的action路径  
        error: function () {//请求失败处理函数  
            alert('请求失败');  
        },  
        success:function(data){ //请求成功后处理函数。  
        	//alert(data);
	        var json=JSON.parse(data);
		    var content=json.words_result;
	        if(typeOcr=="idcard"){
	        	if(json.image_status == "normal"){
		            var name=content["姓名"].words;
		            var sex=content["性别"].words;
		            var birthday=content["出生"].words;
		            var address=content["住址"].words;
		            var nation=content["民族"].words;
		            var idcard=content["公民身份号码"].words;
		            $("#name").val(name);
		            $("#sex").val(sex);
		            $("#birthday").val(birthday);
		            $("#address").val(address);
		            $("#nation").val(nation);
		            $("#idcard").val(idcard);
		            var image="http://127.0.0.1:8080/"+json.imgSrc;
		            //alert(image);  
		            $("#showimg2").get(0).src=image;
		            var showimg=$("#showimg2").attr("src");
		            if(showimg !=""){
		            	$("#showspan2").hide();
		            }
	        	}else{
	        		alert('材料识别不正确,可能存在一下问题:\n1.上传的材料与所需材料是否一致。\n2.材料拍照是否清晰。\n3.拍照的角度是否端正。');
	        	}  
	        	//$("#upload").replaceWith('<input type="file" name="upload" id="upload2" style="display: none;"/>');
	        }else if(typeOcr=="business_license"){
	        	var legalPerson  = content["法人"].words;
	            var addr  = content["地址"].words;
	            var registerDate  = content["成立日期"].words;
	            var unitName  = content["单位名称"].words;
	            var idNumber  = content["证件编号"].words;
	            var socialCreditCode  = content["社会信用代码"].words;
	            var validDate  = content["有效期"].words;
	            $("#legalPerson").val(legalPerson);
	            $("#addr").val(addr);
	            $("#registerDate").val(registerDate);
	            $("#unitName").val(unitName);
	            $("#idNumber").val(idNumber);
	            $("#socialCreditCode").val(socialCreditCode);
	            $("#validDate").val(validDate);
	            var image="http://127.0.0.1:8080/"+json.imgSrc;
	            //alert(image);  
	            $("#showimg").get(0).src=image;
	            var showimg=$("#showimg").attr("src");
	            if(showimg !=""){
	            	$("#showspan").hide();
	            } 
	        }
        }
    }); 
}
</script>
<div style='margin-top: 30px;'>
<input type='file' name="upload" id="upload" style='display: none;' onchange="changecard('upload','idcard')"/>
<input type='button' class='btn btn-success' onclick="selectFile('upload')" value='文件上传' />
</div>
<div style='margin-top: 30px;'>
   <input type='file' name="upload" id="upload2" style='display: none;' onchange="changecard('upload2','business_license')"/>
   <input type='button' class='btn btn-success' onclick="selectFile('upload2')" value='文件上传' />
</div>

FormData

jsp页面

FormData方法
<script type="text/javascript">
function selectFile(id) {
	$("#"+id).click();
};
function changecard(id,typeOcr) {
    //企业法人身份证
    var fileObj=document.getElementById(id).files[0];
    alert(fileObj);
    var formFile = new FormData();
    formFile.append("file", fileObj);
    formFile.append("filetype", typeOcr);
	$.ajax({
        url: "get/creditinfo_baiduOcr.action",
        data: formFile,
        //enctype: 'multipart/form-data',
        type: "Post",
        dataType: "json",
        cache: false,//上传文件无需缓存
        processData: false,//用于对data参数进行序列化处理 这里必须false
        contentType: false, //必须
        success: function (data) {
            //alert(data);
	        var json=JSON.parse(data);
		    var content=json.words_result;
	        if(typeOcr=="idcard"){
	        	if(json.image_status == "normal"){
		            var name=content["姓名"].words;
		            var sex=content["性别"].words;
		            var birthday=content["出生"].words;
		            var address=content["住址"].words;
		            var nation=content["民族"].words;
		            var idcard=content["公民身份号码"].words;
		            $("#name").val(name);
		            $("#sex").val(sex);
		            $("#birthday").val(birthday);
		            $("#address").val(address);
		            $("#nation").val(nation);
		            $("#idcard").val(idcard);
		            var image="http://127.0.0.1:8080/"+json.imgSrc;
		            $("#showimg2").get(0).src=image;
		            var showimg=$("#showimg2").attr("src");
		            if(showimg !=""){
		            	$("#showspan2").hide();
		            }
	        	}else{
	        		alert('材料识别不正确,可能存在一下问题:\n1.上传的材料与所需材料是否一致。\n2.材料拍照是否清晰。\n3.拍照的角度是否端正。');
	        	}  
	        }else if(typeOcr=="business_license"){
	        	var legalPerson  = content["法人"].words;
	            var addr  = content["地址"].words;
	            var registerDate  = content["成立日期"].words;
	            var unitName  = content["单位名称"].words;
	            var idNumber  = content["证件编号"].words;
	            var socialCreditCode  = content["社会信用代码"].words;
	            var validDate  = content["有效期"].words;
	            $("#legalPerson").val(legalPerson);
	            $("#addr").val(addr);
	            $("#registerDate").val(registerDate);
	            $("#unitName").val(unitName);
	            $("#idNumber").val(idNumber);
	            $("#socialCreditCode").val(socialCreditCode);
	            $("#validDate").val(validDate);
	            var image="http://127.0.0.1:8080/"+json.imgSrc;
	            //alert(image);  
	            $("#showimg").get(0).src=image;
	            var showimg=$("#showimg").attr("src");
	            if(showimg !=""){
	            	$("#showspan").hide();
	            } 
	        }
        },
        error: function () {//请求失败处理函数  
            alert('请求失败');  
        }, 
    })
}
</script>
<div style='clear: both;'>
        <div class='leftContainer' style='width:50%;float:left;text-align: center'>
            <p style='text-align: center;font-size: 18px;font-weight: bolder;margin-top: 20px;'>企业法人身份证</p>
			<div style='display: inline-block;width: 320px;margin-top: 20px;line-height:200px;color:#ABABAB;font-size:30px;border-radius: 10px; border :2px solid #ABABAB'>
           		<span id="showspan2">企业法人身份证</span>
                <img width='100%' src="" id="showimg2"/>
            </div>
            <div style='margin-top: 30px;'>
                <input type='file' name="upload" id="upload" style='display: none;' onchange="changecard('upload','idcard')"/>
                <input type='button' class='btn btn-success' onclick="selectFile('upload')" value='文件上传' />
            </div>
        </div>

        <div class='right-container'>
            <p style='text-align: right;font-size: 18px;font-weight: bolder;margin-top: 20px;width: 86%'>企业法人身份证
                <span class="up-fill-instruction">(上传附件后以下信息自动填充)</span>
            </p>
            <div style='width:80%;display: inline-block;text-align: right;margin-top: 20px;'>
                <div class='row'>

					<form id="idCardForm" name="idCardForm" method="post">
                    <div class="row-footer">
                        <div style='clear: both;'></div>
                        <label class='control-label col-sm-3 row-footer-label' >姓名:</label>
                        <div class='formControls col-xs-7 col-sm-9 row-footer-input'>
                            <input type='text' class='form-control' placeholder='姓名' id='name'name='name'>
                            <input type='hidden' class='form-control' placeholder='图片' id='imgIdcard'name='imgIdcard'>
                        </div>
                    </div>

                    <div class="row-footer">
                        <div style='clear: both;'></div>
                        <label class='control-label col-sm-3 row-footer-label'>性别:</label>
                        <div class='formControls col-xs-7 col-sm-9 row-footer-input'>
                            <input type='text' class='form-control' placeholder='性别' id='sex'name='sex'>
                        </div>
                    </div>

                    <div class="row-footer">
                        <div style='clear: both;'></div>
                        <label class='control-label col-sm-3 row-footer-label'>生日:</label>
                        <div class='formControls col-xs-7 col-sm-9 row-footer-input'>
                            <input type='text' class='form-control' placeholder='生日'  id='birthday'name='birthday'>
                            <!-- <input class='form-control' id="datePicker1" name="fillContentList" type="text"  readonly="readonly" placeholder="生日" onclick="bindDate1()"/> -->
                        </div>
                    </div>

                    <div class="row-footer">
                        <div style='clear: both;'></div>
                        <label class='control-label col-sm-3 row-footer-label'>住址:</label>
                        <div class='formControls col-xs-7 col-sm-9 row-footer-input'>
                            <input type='text' class='form-control' placeholder='住址' id='address'name='address'>
                        </div>
                    </div>

                    <div class="row-footer">
                        <div style='clear: both;'></div>
                        <label class='control-label col-sm-3 row-footer-label'>民族:</label>
                        <div class='formControls col-xs-7 col-sm-9 row-footer-input'>
                            <input type='text' class='form-control' placeholder='民族' id='person'name='person'>
                        </div>
                    </div>

                    <div class="row-footer">
                        <div style='clear: both;'></div>
                        <label class='control-label col-sm-3 row-footer-label'>公民身份号码:</label>
                        <div class='formControls col-xs-7 col-sm-9 row-footer-input'>
                            <input type='text' class='form-control' placeholder='公民身份号码' id='idcard'name='idcard'>
                        </div>
                    </div>
                    <div class="row-footer">
                        <div style='clear: both;'></div>
                        <label class='control-label col-sm-3 row-footer-label'>手机号码:</label>
                        <div class='formControls col-xs-7 col-sm-9 row-footer-input'>
                            <input type='text' class='form-control' placeholder='手机号码' id='phone'name='phone'>
                        </div>
                    </div>
				</form>

                </div>
            </div>
        </div>
    </div>

action

    private File file;
    // 文件的名称
    private String fileFileName;
    // 文件的MIME的类型
    private String fileContentType;
    private String success;
	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}
	public String getSuccess() {
    	return success;
    }
    public void setSuccess(String success) {
    	this.success = success;
    }
    /**
	 * 百度ocr身份证营业执照识别
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	//TODO
	public String baiduOcr() {
		// 初始化一个AipOcr
		AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
		// 可选:设置网络连接参数
		client.setConnectionTimeoutInMillis(2000);
		client.setSocketTimeoutInMillis(60000);
		// 传入可选参数调用接口
		HashMap<String, String> options = new HashMap<String, String>();
		options.put("detect_direction", "true");
		options.put("detect_risk", "false");
		// front - 身份证含照片的一面 back - 身份证带国徽的一面
		String idCardSide = "front";
		// 保存图片到本地服务器路径
		//String filetype = request.getParameter("filetype");
		String dirPath = request.getSession().getServletContext()
				.getRealPath("/");
		File dirFile = new File(dirPath);

		String datedir = DateTools.getStringFromDate(new Date(),"yyyy/MM/dd");

		String filepathdir = "tempFile"+ File.separator+ filetype + File.separator + datedir+ File.separator;

		File serverFiledir = new File(dirFile.getParent() + File.separator+ "sxserver" + File.separator+ filepathdir);
		if(!serverFiledir.exists()){
			serverFiledir.mkdirs();
		}
		String fileName=null;
			fileName = new Date().getTime()+ (int) (Math.random() * 10000)+ fileFileName.substring(fileFileName.lastIndexOf("."));
		/*}*/
		File targetFile = new File(serverFiledir, fileName);
		//springMVC框架下,利用MultipartFile 的 transferTo 将一个文件上传到服务器:
		//file.transferTo(targetFile);
		//将图片上传到服务器
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream(file.getPath());
			fos = new FileOutputStream(targetFile.getPath());
	
			byte[] buffer = new byte[1024];
			int len = 0;
	
			while ((len = fis.read(buffer)) != -1) {
			fos.write(buffer,0, len);
			fos.flush();
		}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fis.close();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		JSONObject json=new JSONObject();
		if(filetype.equals("idcard")) {
			json = client.idcard(targetFile.getPath(), idCardSide, options);
		}else {
			json =client.businessLicense(targetFile.getPath(), options);
		}
		System.out.println(json.toString());
		
		String src = File.separator + "sxserver"+ File.separator + filepathdir + fileName;
		json.put("imgSrc", src);
		success = json.toString();
		return "success";
	}

struts.xml

<!-- 企业法人身份证营业执照列表 -->
<action name="idcard_*" class="idcardAction" method="{1}" >
	    <result name="success" type="json">
                <param name="root">success</param>
           	</result>
           	<!-- <result name="add">/WEB-INF/get/qyrz.jsp</result> -->
            <result name="result" type="json">
            	<param name="root">result</param>
           	</result>
            <result name="qyrz">/WEB-INF/back/qyrz.jsp</result>
</action>

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值