WEB頁面通過ajax進行圖片上傳實例(附代碼)


背景:公司需要一個簽約頁面,支持拍照或選擇圖片上傳,應用場景主要在手機端.

頁面代碼:

 1 <!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="#" 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代碼:

<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');
		}
	});
});

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>  

后端代碼:

import 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('.'));
 
結束.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM