1. 程式人生 > >freemarker+springMVC+ajaxfileupload實現非同步圖片上傳(單張)

freemarker+springMVC+ajaxfileupload實現非同步圖片上傳(單張)

第一步:下載JQuery的JS檔案ajaxfileupload.js 並引入到freemarker

第二步:freemarker頁面

<span style="font-size:18px;"><!DOCTYPE html>
<html lang="zh-cn" class="hb-loaded">

    <head>  
    <meta http-equiv="pragma" content="no-cache">  
    <meta http-equiv="cache-control" content="no-cache">  
    <meta http-equiv="expires" content="0">      
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
    <meta http-equiv="description" content="This is my page">  
    <!-- 
    <link rel="stylesheet" type="text/css" href="styles.css"> 
    -->  
    <script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
    <script language="javascript" src="js/ajaxfileupload.js" > </script>   
    <script type="text/javascript">    
	 	function preview(file){  
	 		var prevDiv = document.getElementById('preview');  
	 		if (file.files && file.files[0]){  
	 			var reader = new FileReader();  
	 			reader.onload = function(evt){  
					prevDiv.innerHTML = '<img src="' + evt.target.result + '" />';  
				}    
				reader.readAsDataURL(file.files[0]);  
			}else{  
				prevDiv.innerHTML = '<div class="img" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\'' + file.value + '\'"></div>';  
			}  
	 	}  
	</script> 
    <script>
 	    //新建或編輯 儲存提交  
		function submitPic(){  
		    var type="1";//展示圖片  
		    var f = $("#file").val();  
		    if(f==null||f==""){  
		        $("#picTip").html("<span style='color:Red'>錯誤提示:上傳檔案不能為空,請重新選擇檔案</span>");  
		        return false;  
		      }else{  
		       var extname = f.substring(f.lastIndexOf(".")+1,f.length);  
		       extname = extname.toLowerCase();//處理了大小寫  
		       if(extname!= "jpeg"&&extname!= "jpg"&&extname!= "gif"&&extname!= "png"){  
		         $("#picTip").html("<span style='color:Red'>錯誤提示:格式不正確,支援的圖片格式為:JPEG、GIF、PNG!</span>");  
		         return false;  
		        }  
		      }  
		     var file = document.getElementById("file").files;    
		     var size = file[0].size;  
		     if(size>2097152){  
		          $("#picTip").html("<span style='color:Red'>錯誤提示:所選擇的圖片太大,圖片大小最多支援2M!</span>");   
		          return false;  
		      }  
		    ajaxFileUploadPic(name,type);  
		}  
  
		function ajaxFileUploadPic() {  
		    $.ajaxFileUpload({  
		        url : 'saveorupdate.action?type=1', //用於檔案上傳的伺服器端請求地址  
		        secureuri : false, //一般設定為false  
		        fileElementId : 'file', //檔案上傳空間的id屬性  <input type="file" id="file" name="file" />  
		        type : 'post',  
		        dataType : 'json', //返回值型別 一般設定為json  
		        success : function(data, status) //伺服器成功響應處理函式  
		        {  
		        	 var path = data.Path;
		        	 //alert(data.filePath);
		             $("#picTip").html("<span style='color:Red'>圖片上傳成功!圖片地址為:path</span>");
		        },  
		        error : function(data, status, e)//伺服器響應失敗處理函式  
		        {  
		             //alert(data.filePath);
		             $("#picTip").html("<span style='color:Red'>圖片上傳成功!</span>");
		        }  
		    });  
		    return false;  
}      
</script>
  </head>  
<body>
    <div id="uploadPicWindow" class="easyui-window" title="上傳圖片"  style="width:420px;height:220px;padding:20px;background:#fafafa;" data-options="iconCls:'icon-save',closable:true, collapsible:true,minimizable:true,maximizable:true">  
        <form id="picForm" action="" method="post">  
            <div id="preview"></div>
            <div style="margin-bottom:20px">  
              	  選擇圖片:  
                <input type="file" name="file" id="file" data-options="prompt:'Choose a file...'" style="width:80%" onchange="preview(this);"/>  
            </div>  
            <div id="picTip"></div>  
            <div id="formWindowfooterPic1" style="padding:5px;text-align:right;">   
                <a href="#" onclick="submitPic();" class="easyui-linkbutton" data-options="iconCls:'icon-save'">提交</a>  
            </div>  
        </form>  
    </div>  
</body>

</html></span>

第三步:Controller

<span style="font-size:18px;">@RequestMapping(value="saveorupdate",method = RequestMethod.POST)
	@ResponseBody  
	public String upload_yz(HttpServletRequest request) throws Exception {

	    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
	    MultipartFile file = null;  
	    file = multipartRequest.getFile("file");// 獲取上傳檔名  
	    String uploadUrl = uploadService.uploadFile(file, request);
	    return "{\"filePath\":\""+uploadUrl+"\"}";  
	}</span>
第四步:Service
<span style="font-size:18px;"><span style="white-space:pre">	</span>/**
	 * 上傳檔案
	 * @param file	檔案
	 * @param folder	資料夾名稱
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public String uploadFile(MultipartFile file, HttpServletRequest request) throws IOException {
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String rootPath = request.getRealPath("/");
		String prefix = uploadUrlsConfigurer.getContextProperty(request);
		String datePath = format.format(new Date());
		String appPath = prefix+"/"+datePath;
		FileUtils.createFilePath(request.getRealPath("/"), appPath);
		String fileName = Identities.uuid2() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		/*
		 * /upload/other/2015-04-15/cea78319e0ea4756b29de05b2cc431ab.pdf
		 * */
		FileCopyUtils.copy(file.getBytes(), new File(request.getRealPath("/") + appPath+"/"+fileName));
		return "/" + appPath+"/"+fileName;
	}</span>

附頁面效果: