WEB页面通过ajax进行图片上传实例(附代码)

背景:公司需要一个签约页面,支持拍照或选择图片上传,应用场景主要在手机端.

页面代码:

<!DOCTYPE html>
 2 <html>
 3     <head >
 4         <meta charset="utf-8"  name="viewport" content="width=device-width, initial-scale=0.8 minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes" />
 5         <title></title>
 6         <script src="js/jquery-1.12.4.min.js" type="text/javascript" charset="utf-8"></script>
 7         <link rel="stylesheet" type="text/css" href="css/index.css"/>
8 </head> 9 <body> 10 <header> 11 <!-- <a href="https://zhishitu.com/" target="_blank" class="logo"></a> --> 12 <div class="desc">欢迎签约</div> 13 </header> 14 <section> 15 <form id="upload-form" enctype="multipart/form-data"> 16 <div class="register-box"> 17 <label for="username" class="other_label">真 实 姓 名 18 <input maxlength="20" name ="shortName" type="text" placeholder="输入真实姓名"/> 19 </label> 20 <div class="tips"> 21 22 </div> 23 </div> 24 <div class="register-box"> 25 <label for="username" class="other_label">证 件 号 码 26 <input maxlength="20" name = "crpIdNo" type="text" placeholder="输入证件号码"/> 27 </label> 28 <div class="tips"> 29 30 </div> 31 </div> 32 <div class="register-box"> 33 <label for="username" class="other_label">手 机 号 码 34 <input maxlength="20" name = "mobilePhone" type="text" placeholder="输入手机号"/> 35 </label> 36 <div class="tips"> 37 38 </div> 39 </div> 40 <div id="checkResult"></div> 41 <div class="register-box"> 42 <label for="username" class="other_label">银 行 卡 号 43 <input maxlength="20" name = "bankNumber" type="text" placeholder="输入银行卡号"/> 44 </label> 45 <div class="tips"> 46 47 </div> 48 </div> 49 <!-- 身份证正面 --> 50 <div class="register-box"> 51 <!-- capture="camera" --> 52 <label for="username" class="other_label">身 份 证 正 面 53 <input maxlength="20" id = "idcard_positive" name = "idcard_positive" type="file" accept="image/*" placeholder="身份证正面"/> 54 </label> 55 <div class="tips"> 56 57 </div> 58 </div> 59 <!-- 身份证反面 --> 60 <div class="register-box"> 61 <label for="username" class="other_label">身 份 证 反 面 62 <input maxlength="20" id = "idcard_reverse" name = "idcard_reverse" type="file" accept="image/*" placeholder="身份证反面"/> 63 </label> 64 <div class="tips"> 65 66 </div> 67 </div> 68 <div class="arguement"> 69 <input type="checkbox" id="xieyi"/> 70 阅读并同意 71 <a href="#">《服务合作协议》</a> 72 <div class="tips"> 73 74 </div> 75 </div> 76 </div> 77 78 <div class="submit_btn"> 79 <button type="button" onclick="go()" id="submit_btn">立 即 签 约</button> 80 </div> 81 </form> 82 </section> 83 <script src="js/index.js" type="text/javascript" charset="utf-8"></script> 84 85 </body> 86 </html>
知识兔

js代码:

lt;script type="text/javascript">

$(function(){
	 
	//聚焦失焦input
	$('input').eq(0).focus(function(){
		if($(this).val().length==0){
			$(this).parent().next("div").text("支持中文,字母,数字,'-','_'的多种组合");
		}
	});

	//input各种判断
	//姓名:
	$('input').eq(0).blur(function(){
		if($(this).val().length==0){
			$(this).parent().next("div").text("真实姓名不能为空");
			$(this).parent().next("div").css("color",'red');
		}
	});
	//身份证
	$('input').eq(1).blur(function(){
		if($(this).val().length==0){
			$(this).parent().next("div").text("身份证号不能为空");
			$(this).parent().next("div").css("color",'red');
		}	
	});
//	银行卡
	$('input').eq(3).blur(function(){
		if($(this).val().length==0){
			$(this).parent().next("div").text("银行卡不能为空");
			$(this).parent().next("div").css("color",'red');
		}
	});
//	手机号
	/*$('input').eq(2).blur(function(){
		if($(this).val().length==0){
			$(this).parent().next("div").text("手机号不能为空");
			$(this).parent().next("div").css("color",'red');
		}else if($(this).val().substr(0,3)!=138&&$(this).val().substr(0,3)!=189&&$(this).val().substr(0,3)!=139&&$(this).val().substr(0,3)!=158&&$(this).val().substr(0,3)!=188&&$(this).val().substr(0,3)!=157||$(this).val().length!=11){
			$(this).parent().next("div").text("手机号格式不正确");
			$(this).parent().next("div").css("color",'red');
		}else{
			$(this).parent().next("div").text("");
		}		
	});*/

	//	提交按钮
	/*$("#submit_btn").click(function(e){	
		console.log("点击提交按钮");
		for(var j=0 ;j<4;j++){
			if($('input').eq(j).val().length==0){				
				$('input').eq(j).focus();				
				if(j==4){
					$('input').eq(j).parent().next().next("div").text("此处不能为空");
					$('input').eq(j).parent().next().next("div").css("color",'red');
					e.preventDefault();
					return;
				}
				$('input').eq(j).parent().next(".tips").text("此处不能为空");
				$('input').eq(j).parent().next(".tips").css("color",'red');	
				e.preventDefault();
				return;
			}			
		};
		
		 var s = $("#xieyi")[0].checked;
		 alert(s);
		//协议
		if($("#xieyi")[0].checked){

			var shortName = $("input[name='shortName']")[0].value;
			var crpIdNo = $("input[name='crpIdNo']")[0].value;
			var mobilePhone = $("input[name='mobilePhone']")[0].value;
			var bankNumber = $("input[name='bankNumber']")[0].value;
			//此处如果有多个name='shortName',则获得的为数组,通过[0]的方式取值第一个,以此类推
			alert("shortName:"+shortName+"--"+"crpIdNo:"+crpIdNo+"--"+
					"mobilePhone:"+mobilePhone+"--"+"bankNumber:"+bankNumber);
			 页面信息填写成功走签约接口
			console.log("shortName:"+shortName+"--"+"crpIdNo:"+crpIdNo+"--"+
					"mobilePhone:"+mobilePhone+"--"+"bankNumber:"+bankNumber);
			$.ajax({
			    //请求方式
			    type:'POST',
			    //发送请求的地址
			    url:'http://localhost:8095/shb_partner/SignContractAction/SignContract.action',
			    //服务器返回的数据类型
//			    dataType:'json',
			    //发送到服务器的数据,对象必须为key/value的格式,jquery会自动转换为字符串格式
			    data:{
			    		'shortName':shortName,
		             	'mobilePhone':mobilePhone,
		             	'crpIdNo':crpIdNo,
		             	'bankNumber':	bankNumber
		             	
			    },
			    success:function(data){
			        //请求成功函数内容
			    	
			    	alert("请求成功");
			    	alert(data);
			    },
			    error:function(jqXHR){
			        //请求失败函数内容
			    	alert("请求失败");
			    }
			    
			    error: function (data){ 
			    	console.log("1234");
	             		$.messager.alert('消息',"注册失败",'error');
	             	}, 
	             success: function (data){
					console.log("123");
					console.log("jsonString");
	            	 alert(data);
	            	 e.preventDefault();
		             	}
			});
			
		}else{			
			$("#xieyi").next().next(".tips").text("请阅读协议");
			$("#xieyi").next().next(".tips").css("color",'red');
			e.preventDefault();
			return;
		}
	});*/
	

});

function go(){
	console.log("点击提交按钮");
			
	if($("#xieyi")[0].checked){
			for(var j=0 ;j<4;j++){
			if($('input').eq(j).val().length==0){				
				$('input').eq(j).focus();				
				if(j==4){
					$('input').eq(j).parent().next().next("div").text("此处不能为空");
					$('input').eq(j).parent().next().next("div").css("color",'red');
					return;
				}
				$('input').eq(j).parent().next(".tips").text("此处不能为空");
				$('input').eq(j).parent().next(".tips").css("color",'red');	
				return;
			}			
		};		
			
		var form = document.getElementById("upload-form");//获取表单的数据
		var formdata = new FormData( form );//格式化表单数据
		
			console.log("格式化表单数据完成"+formdata);
					
			$.ajax({
			    //请求方式
			    type:'POST',
  				processData: false,// 告诉jQuery不要去处理发送的数据
  			    contentType: false,// 告诉jQuery不要去设置Content-Type请求头
  			    /* dataType: 'json', */ //设置为返回的数据类型
  			    //发送请求的地址
			    url:'http://localhost:8095/hk_partner/SignContractAction/SignContract.action',
			    data:formdata,
	            success: function(result){
	            console.log("响应成功");
	            	 alert(result);
		        }
			});
				console.log("ajax请求完成");
				
				}else{
			$("#xieyi").next().next(".tips").text("请阅读协议");
			$("#xieyi").next().next(".tips").css("color",'red');
			e.preventDefault();
			return;
			}	
			}
</script>  
知识兔

后端代码:

mport org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


 public void SignContract(HttpServletRequest request,HttpServletResponse response) {
        
           
			String shortName  = request.getParameter("shortName");
			String bankNumber  = request.getParameter("bankNumber");
			String crpIdNo  = request.getParameter("crpIdNo");
			String mobilePhone  = request.getParameter("mobilePhone");
			MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
			MultipartFile positive  =	mRequest.getFile("idcard_positive");//身份证正面
			MultipartFile reverse  =	mRequest.getFile("idcard_reverse");//身份证反面
			try {
				if(positive.getSize()==0 ) {
					outPrint(response,"需上传身份证正面");
					return;
				};
				if(reverse.getSize()==0) {
					outPrint(response,"需上传身份证正面");
					return;
				};
			}catch (Exception e) {
				return;
			}

}

public static  void outPrint(HttpServletResponse response,Object obj) throws IOException{
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("progma","no-cache");
		response.setHeader("Cache-Control","no-cache");
		PrintWriter out = response.getWriter();
		out.print(obj);
		out.flush();
		out.close();
	}
	
知识兔

  

  • 1.页面和js部分:
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=0.8 minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes" />
描述:自适应设备宽度,初始化缩放倍率0.8,最小缩放0.5,最高2.0.用户缩放可调.
  • 关于form的enctype属性.描述如下
<form id="upload-form"  enctype="multipart/form-data"> 
描述
application/x-www-form-urlencoded
在发送前编码所有字符(默认)
multipart/form-data
不对字符编码。
在使用包含文件上传控件的表单时,必须使用该值。
text/plain
空格转换为 "+" 加号,但不对特殊字符编码。
  • jQuery选择器的问题
<input type="checkbox" id="xieyi"/>
对于jQuery判断checkbox是否被选中 var status = $("#xieyi")[0].checked  ;  //选中 status = true  未选中false
if($('input').eq(j).val().length==0){ ....}    //jQuery 的 eq选择器  描述: input类型的第j个元素的值的长度    
// eq选择器用法:    eq() 选择器选取带有指定 index 值的元素。
// index 值从 0 开始,所有第一个元素的 index 值是 0(不是 1)。
focus()  和 blur()  分别是聚焦 和 失焦 函数
  • 2.java代码:
  • 配置上传spring-mvc.xml
   <!-- 上传文件设置 -->
          <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
                     <property name="defaultEncoding" value="UTF-8" />
                     <property name="maxUploadSize" value="32505856" /><!-- 上传文件大小限制为31M,31*1024*1024 -->
                     <property name="maxInMemorySize" value="4096" />
          </bean>
  • 获取文件1,通过参数名获取
                    //获取图片参数: MultipartFile  这个类一般是用来接受前台传过来的文件
                     MultipartHttpServletRequest mRequest =  (MultipartHttpServletRequest) request;//// 转换request,解析出request中的文件 
                     MultipartFile positive  =   mRequest.getFile("idcard_positive");//身份证正面
                     MultipartFile reverse   =   mRequest.getFile("idcard_reverse");//身份证反面
  • 获取文件2,遍历获取
       // 转换request,解析出request中的文件
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
       // 获取文件map集合
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        String fileName = null;
        // 循环遍历,取出单个文件
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取单个文件
            MultipartFile mf = entity.getValue();
            // 获得原始文件名
            fileName = mf.getOriginalFilename();
            // 截取文件类型; 这里可以根据文件类型进行判断
            String fileType = fileName.substring(fileName.lastIndexOf('.'));
            // 截取上传的文件名称
            String newFileName = fileName.substring(0, fileName.lastIndexOf('.'));
计算机