1. 程式人生 > >SpringMVC+ajaxFileUpload 相容IE瀏覽器實現非同步上傳圖片

SpringMVC+ajaxFileUpload 相容IE瀏覽器實現非同步上傳圖片

第一次出差到深圳,幫朋友給一個專案收尾,客戶臨時要求上傳檔案的時候順便上傳封面,所以就想到用非同步上傳的方式,然後在前端預覽上傳的圖片,於是就用到了ajaxFileUpload”這一款基於“jquery”的上傳外掛,剛拿到手的時候去網上查了一下他的用法,然後理所當然的在返回值的時候用json傳遞資料,但是這個時候,IE瀏覽器開始不相容了,報了一個什麼語法錯誤這樣一個錯,後來才發現,IE瀏覽器好像不支援回傳json格式的資料,只能傳回json字串然後轉成json物件,於是在這裡記錄一下程式碼,以便重複利用。

js部分

		function deletimg(){
			$("#img").css("display","none");
			$("#imgText").val("");
			$("#img")[0].src="";
			$("#imgfile").css("display","block");
			$("#delimg").css("display","none");
		}
		function uploadImg(){
			var f = $("#imgfile").val();
			var extname = f.substring(f.lastIndexOf(".")+1,f.length);
			extname = extname.toLowerCase();//處理了大小寫
			if(extname!= "jpeg"&&extname!= "jpg"&&extname!= "gif"&&extname!= "png"){
				alert("格式不正確,支援的圖片格式為:JPEG、GIF、PNG!");
				return false;
			}
			var file = document.getElementById("imgfile").files;  
			var size = file[0].size;
			if(size>2097152){
				alert("所選擇的圖片太大,圖片大小最多支援2M!"); 
				return false;
			}
			ajaxFileUploadPic();
		}

		function ajaxFileUploadPic() {
			$.ajaxFileUpload({
				url : 'fileupload/uploadImg', //用於檔案上傳的伺服器端請求地址
				secureuri : false, //一般設定為false
				fileElementId : "imgfile", //檔案上傳空間的id屬性  <input type="file" id="file" name="file" />
				type : 'post',
				dataType : 'text', //返回值型別 一般設定為json
				success : function(data, status) //伺服器成功響應處理函式
				{

					alert(data);
					var obj = eval('(' + data + ')');

					if(obj.result=="success"){
						$("#img").css("display","block");
						$("#imgText").val(obj.url);
						$("#img")[0].src=obj.url;
						$("#imgfile").css("display","none");
						$("#delimg").css("display","block");
					}else{
						alert("圖片上傳失敗,請重試。錯誤原因:"+obj.msg);
					}
				    
				},
				error : function(data, status, e)//伺服器響應失敗處理函式
				{
					alert("圖片上傳失敗,請重試。");
					//alert(data);
					//alert(e);
				    
				}
			});
			return false;
		}

jsp部分
<input type="file" name="imgfile" id="imgfile" placeholder="請選擇封面檔案" onchange="uploadImg()">
<img id="img" style="height:100px;width:auto;display:none;">
<input type="hidden" id="imgfileText">
<input type="button" id="delimg" onclick="deletimg()" value="刪除圖片" style="display:none">
											
Controller部分
	@RequestMapping(value = "/uploadImg")  
    public Map<String, Object> uploadImg2(HttpServletRequest request,  
            HttpServletResponse response, MultipartHttpServletRequest req) {  

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile uploadFile = null;
		
		uploadFile = multipartRequest.getFile("imgfile");// 獲取上傳檔名
        response.setContentType("text/html;charset=utf-8");  
        try {  
    		//檔案儲存目錄路徑
    		String savePath = request.getSession().getServletContext().getRealPath("/") + "uploadFiles/KJIMG/";

    		//檔案儲存目錄URL
    		String saveUrl  = request.getContextPath() + "/uploadFiles/KJIMG/";

    		//檢查目錄
    		File uploadDir = new File(savePath);
    		if(!uploadDir.isDirectory()){
    			uploadDir.mkdirs();
    		}
    		//檢查目錄寫許可權
    		if(!uploadDir.canWrite()){
    			response.getWriter().write("{\"result\":\"error\",\"msg\":\"上傳目錄沒有寫許可權。\"}"); 
    			return null;
    		}
    		
    		String dirName = request.getParameter("dir");
    		if (dirName == null) {
    			dirName = "image";
    		}
    		//建立資料夾
    		savePath += dirName + "/";
    		saveUrl += dirName + "/";
    		File saveDirFile = new File(savePath);
    		if (!saveDirFile.exists()) {
    			saveDirFile.mkdirs();
    		}
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    		String ymd = sdf.format(new Date());
    		savePath += ymd + "/";
    		saveUrl += ymd + "/";
    		File dirFile = new File(savePath);
    		if (!dirFile.exists()) {
    			dirFile.mkdirs();
    		}
    		String fileName = uploadFile.getOriginalFilename();
    		String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
    		
    		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
    		String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
    		BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(savePath + newFileName));
    		FileCopyUtils.copy(uploadFile.getInputStream(), outputStream);
    		
            response.getWriter().write("{\"result\":\"success\",\"url\":\""+saveUrl + newFileName+"\"}"); 
        } catch (Exception e) {  
            e.printStackTrace();  
            try {  
                response.getWriter().write("{\"result\":\"error\",\"msg\":\""+e.getMessage()+"\"}");  
            } catch (IOException e1) {  
                e1.printStackTrace();  
            }  
        }  
  
        return null;  
    }  


ajaxFileUpload.js部分
jQuery.extend({
	handleError: function (s, xhr, status, e) {
        if (s.error) {
            s.error.call(s.context || s, xhr, status, e);
        }
        if (s.global) {
            (s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError", [xhr, s, e]);
        }
    },
    httpData: function (xhr, type, s) {
        var ct = xhr.getResponseHeader("content-type"),
xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
        if (xml && data.documentElement.tagName == "parsererror")
            throw "parsererror";
        if (s && s.dataFilter)
            data = s.dataFilter(data, type);
        if (typeof data === "string") {
            if (type == "script")
                jQuery.globalEval(data);
            if (type == "json")
                data = window["eval"]("(" + data + ")");
        }
        return data;
    },
    createUploadIframe: function(id, uri)
	{
			//create frame
            var frameId = 'jUploadFrame' + id;
            
            if(window.ActiveXObject) {
                var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
                if(typeof uri== 'boolean'){
                    io.src = 'javascript:false';
                }
                else if(typeof uri== 'string'){
                    io.src = uri;
                }
            }
            else {
                var io = document.createElement('iframe');
                io.id = frameId;
                io.name = frameId;
            }
            io.style.position = 'absolute';
            io.style.top = '-1000px';
            io.style.left = '-1000px';

            document.body.appendChild(io);

            return io			
    },
    createUploadForm: function(id, fileElementId)
	{
		//create form	
		var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');	
		var oldElement = $('#' + fileElementId);
		var newElement = $(oldElement).clone();
		$(oldElement).attr('id', fileId);
		$(oldElement).before(newElement);
		$(oldElement).appendTo(form);
		//set attributes
		$(form).css('position', 'absolute');
		$(form).css('top', '-1200px');
		$(form).css('left', '-1200px');
		$(form).appendTo('body');		
		return form;
    },

    ajaxFileUpload: function(s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout		
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = s.fileElementId;        
		var form = jQuery.createUploadForm(id, s.fileElementId);
		var io = jQuery.createUploadIframe(id, s.secureuri);
		var frameId = 'jUploadFrame' + id;
		var formId = 'jUploadForm' + id;		
        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ )
		{
			jQuery.event.trigger( "ajaxStart" );
		}            
        var requestDone = false;
        // Create the request object
        var xml = {}   
        if ( s.global )
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function(isTimeout)
		{			
			var io = document.getElementById(frameId);
            try 
			{				
				if(io.contentWindow)
				{
					 xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                	 xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
					 
				}else if(io.contentDocument)
				{
					 xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                	xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
				}						
            }catch(e)
			{
				jQuery.handleError(s, xml, null, e);
			}
            if ( xml || isTimeout == "timeout") 
			{				
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" )
					{
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData( xml, s.dataType );    
                        // If a local callback was specified, fire it and pass it the data
                        if ( s.success )
                            s.success( data, status );
    
                        // Fire the global callback
                        if( s.global )
                            jQuery.event.trigger( "ajaxSuccess", [xml, s] );
                    } else
                        jQuery.handleError(s, xml, status);
                } catch(e) 
				{
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, s] );

                // Handle the global AJAX counter
                if ( s.global && ! --jQuery.active )
                    jQuery.event.trigger( "ajaxStop" );

                // Process result
                if ( s.complete )
                    s.complete(xml, status);

                jQuery(io).unbind()

                setTimeout(function()
									{	try 
										{
											$(io).remove();
											$(form).remove();	
											
										} catch(e) 
										{
											jQuery.handleError(s, xml, null, e);
										}									

									}, 100)

                xml = null

            }
        }
        // Timeout checker
        if ( s.timeout > 0 ) 
		{
            setTimeout(function(){
                // Check to see if the request is still happening
                if( !requestDone ) uploadCallback( "timeout" );
            }, s.timeout);
        }
        try 
		{
           // var io = $('#' + frameId);
			var form = $('#' + formId);
			$(form).attr('action', s.url);
			$(form).attr('method', 'POST');
			$(form).attr('target', frameId);
            if(form.encoding)
			{
                form.encoding = 'multipart/form-data';				
            }
            else
			{				
                form.enctype = 'multipart/form-data';
            }			
            $(form).submit();

        } catch(e) 
		{			
            jQuery.handleError(s, xml, null, e);
        }
        if(window.attachEvent){
            document.getElementById(frameId).attachEvent('onload', uploadCallback);
        }
        else{
            document.getElementById(frameId).addEventListener('load', uploadCallback, false);
        } 		
        return {abort: function () {}};	

    },

    uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if ( type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if ( type == "json" ){
    	  // 因為json資料會被<pre>標籤包著,所以有問題,現在新增以下程式碼,
    	  // update by hzy
    	  var reg = /<pre.+?>(.+)<\/pre>/g; 
    	  var result = data.match(reg);
    	  result = RegExp.$1;
    	  // update end
    	  data = $.parseJSON(result);
    	  // eval( "data = " + data );
    	 }
        // evaluate scripts within html
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();
			//alert($('param', data).each(function(){alert($(this).attr('value'));}));
        return data;
    }
})




Controller部分