1. 程式人生 > >ajax 上傳檔案和form

ajax 上傳檔案和form

1、檔案html,點選顯示

 <div class="col-md-2">
                         <a href="javascript:void(0);" class="thumbnail">
                       		 <img id="picshow" src="../../images/zanwu1.jpg" class="img-responsive">
                       	 </a>
                       	 <a class="file" href="javascript:;">
                       	 <input id="picture" type="file" name="picture" onchange="pic_change(this);"></a>
           			   </div>
/**
 * 點選“選擇檔案”,在img裡顯示上傳的圖片,不需要傳到後臺
 */
var reader = new FileReader();
function pic_change(file){
	var img = document.getElementById('picshow');
	//讀取File物件的資料
	reader.onload = function(evt){
		//data:img base64 編碼資料顯示
		img.width  =  "300";
        img.height =  "200";
		img.src = evt.target.result;
	}
    reader.readAsDataURL(file.files[0]);
}

2、填完form,點選儲存,檔案和其他資訊分步傳到後臺


/***
 * 點選儲存,資訊儲存到Library,圖片儲存到upload
 */
$("#btn_addOfficer").click(function(){
	
	if (validform().form()) {
		//1、驗證兩個口令是否相同
		var psw = $("#psw").val();
		var confirmPsw = $("#confirmPsw").val();
		if(psw == confirmPsw){
			
		 	var s = $('#picture')[0].files[0];  
	        var formData = new FormData();  
	        formData.append("upload", s);  
	        formData.append("who", userId); 
	        formData.append("fileType","行政執法");
			$.ajax({  
		            url: realPath  + "/xzzf/file/uploadFile",  
		            type: 'POST',  
		            cache: false,  
		            data: formData,
			    async :false,
		            processData: false,  
		            contentType: false,  
		            success: function (result) {  
		            	picId = result.msg;//同步時,才可以
					}, 
		        });  
	   alert(picId);
		//3、上傳資訊
		 var formData = $("#addOfficer").serializeObject();
		$.ajax({
			url:realPath+"/xzzf/officer/addLibrary/"+picId,
			type:"post",
			data:JSON.stringify(formData),
			contentType: "application/json",
			success:function(data){	
				//window.location.href="lawofficer.html";
			}
		})
  }else{
	  alert("口令不一致!");
  }
}
})

注意:同步時,才能獲取到傳回的是資料;

3、後臺

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> upload(@RequestParam(value="upload", required=false) MultipartFile file, HttpServletRequest request) throws IOException {
	    Map<String, String> result = new HashMap<String, String>();
	    if (!file.isEmpty()) {
	      //獲取上傳檔案的原名
	        String fileName = file.getOriginalFilename();
	        String who = request.getParameter("who");
	        String fileType = request.getParameter("fileType");
	        //獲取專案存放上傳檔案的路徑
	        String filePath = ProjectPathUtil.UPLOAD_PATH;
	        
	        System.out.println("上傳檔案路徑:" + filePath);
	        
	        InputStream inputStream = file.getInputStream();
	        String savePath = filePath + fileName;
	        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
	        //將檔案存放到專案的指定路徑
	        FileUtils.copyInputStreamToFile(inputStream, new File(savePath));
	        
	        
	        //儲存檔案資訊
	        Upload sysFile = new Upload(fileName, savePath, suffix, who, fileType, LocalDateTime.now());
	        
	        Long fd = fileService.saveFile(sysFile);
	        if (fd != null) {
	            result.put("status", "true");
	            result.put("msg", String.valueOf(fd));//返回上傳檔案後的地址
	            result.put("name", fileName);//返回上傳檔案後的地址
	        } else {
	            result.put("status", "false");
	            result.put("msg", "上傳錯誤");
	        }
	    } else {
	        result.put("status", "false");
            result.put("msg", "上傳錯誤");
	    }
	    
		return result;
	}

@RequestMapping(value="/addLibrary/{picId}",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, String> addLibrary(@PathVariable("picId")String picId,@RequestBody Library library){
		Map<String, String> res = new HashMap<String,String>();
		library.setPicture(picId);
		long pId = lawOfficerService.addLibrary(library);
		res.put("pmsg", String.valueOf(pId));
		return res;
	}