springmvc + ajaxfileupload 实现异步上传文件(图片)

最近在做一个项目需要实现异步上传图片,在网上找了很多资料后,采用了ajaxfileupload可以实现,以下是核心代码:

jsp:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <!-- 上传窗口 -->   
  2.     <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">  
  3.         <form id="picForm" action="" method="post">  
  4.             <div style="margin-bottom:20px">  
  5.                 图片名称:  
  6.                 <input type="text" name="name" id="picName" class="easyui-textbox" style="width:80%" data-options="required:true,validType:'stringCheck'"/>  
  7.             </div>  
  8.             <br/>  
  9.             <div style="margin-bottom:20px">  
  10.                 选择图片:  
  11.                 <input type="file" name="file" id="file" data-options="prompt:'Choose a file...'" style="width:80%"/>  
  12.             </div>  
  13.             <div id="picTip"></div>  
  14.             <div id="formWindowfooterPic1" style="padding:5px;text-align:right;">   
  15.                 <a href="#" onclick="submitPic();" class="easyui-linkbutton" data-options="iconCls:'icon-save'">提交</a>  
  16.             </div>  
  17.         </form>  
  18.     </div>  

js:

[javascript]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //新建或编辑 保存提交  
  2. function submitPic(){  
  3.     if(!$("#picForm").form('validate')){  
  4.         return false;  
  5.     }  
  6.     var projectId = $("#projectId").val();  
  7.     var name=$("#picName").val();  
  8.     var type="1";//展示图片  
  9.     var f = $("#file").val();  
  10.     if(f==null||f==""){  
  11.         $("#picTip").html("<span style='color:Red'>错误提示:上传文件不能为空,请重新选择文件</span>");  
  12.         return false;  
  13.       }else{  
  14.        var extname = f.substring(f.lastIndexOf(".")+1,f.length);  
  15.        extname = extname.toLowerCase();//处理了大小写  
  16.        if(extname!= "jpeg"&&extname!= "jpg"&&extname!= "gif"&&extname!= "png"){  
  17.          $("#picTip").html("<span style='color:Red'>错误提示:格式不正确,支持的图片格式为:JPEG、GIF、PNG!</span>");  
  18.          return false;  
  19.         }  
  20.       }  
  21.      var file = document.getElementById("file").files;    
  22.      var size = file[0].size;  
  23.      if(size>2097152){  
  24.           $("#picTip").html("<span style='color:Red'>错误提示:所选择的图片太大,图片大小最多支持2M!</span>");   
  25.           return false;  
  26.       }  
  27.     ajaxFileUploadPic(projectId,name,type);  
  28. }  
  29.   
  30. function ajaxFileUploadPic(projectId,name,type) {  
  31.     $.ajaxFileUpload({  
  32.         url : '${ctx}/projectPic/saveorupdate.jhtml?projectId='+projectId+'&name='+name+'&type='+type, //用于文件上传的服务器端请求地址  
  33.         secureuri : false//一般设置为false  
  34.         fileElementId : 'file'//文件上传空间的id属性  <input type="file" id="file" name="file" />  
  35.         type : 'post',  
  36.         dataType : 'json'//返回值类型 一般设置为json  
  37.         success : function(data, status) //服务器成功响应处理函数  
  38.         {  
  39.              $("#picList").datagrid('reload');  
  40.              $('#uploadPicWindow').window('close');  
  41.             // alert(data.msg);  
  42.         },  
  43.         error : function(data, status, e)//服务器响应失败处理函数  
  44.         {  
  45.              $("#picList").datagrid('reload');  
  46.              $('#uploadPicWindow').window('close');  
  47.             // alert(data.msg);  
  48.         }  
  49.     });  
  50.     return false;  
  51. }  


ajaxfileupload.js
[javascript]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. jQuery.extend({  
  2.       
  3.     createUploadIframe: function(id, uri)  
  4.     {  
  5.             //create frame  
  6.             var frameId = 'jUploadFrame' + id;  
  7.             var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';  
  8.             if(window.ActiveXObject)  
  9.             {  
  10.                 if(typeof uri== 'boolean'){  
  11.                     iframeHtml += ' src="' + 'javascript:false' + '"';  
  12.   
  13.                 }  
  14.                 else if(typeof uri== 'string'){  
  15.                     iframeHtml += ' src="' + uri + '"';  
  16.   
  17.                 }     
  18.             }  
  19.             iframeHtml += ' />';  
  20.             jQuery(iframeHtml).appendTo(document.body);  
  21.   
  22.             return jQuery('#' + frameId).get(0);              
  23.     },  
  24.     createUploadForm: function(id, fileElementId, data)  
  25.     {  
  26.         //create form     
  27.         var formId = 'jUploadForm' + id;  
  28.         var fileId = 'jUploadFile' + id;  
  29.         var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');      
  30.         if(data)  
  31.         {  
  32.             for(var i in data)  
  33.             {  
  34.                 jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);  
  35.             }             
  36.         }         
  37.         var oldElement = jQuery('#' + fileElementId);  
  38.         var newElement = jQuery(oldElement).clone();  
  39.         jQuery(oldElement).attr('id', fileId);  
  40.         jQuery(oldElement).before(newElement);  
  41.         jQuery(oldElement).appendTo(form);  
  42.   
  43.   
  44.           
  45.         //set attributes  
  46.         jQuery(form).css('position''absolute');  
  47.         jQuery(form).css('top''-1200px');  
  48.         jQuery(form).css('left''-1200px');  
  49.         jQuery(form).appendTo('body');        
  50.         return form;  
  51.     },  
  52.   
  53.     ajaxFileUpload: function(s) {  
  54.         // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout          
  55.         s = jQuery.extend({}, jQuery.ajaxSettings, s);  
  56.         var id = new Date().getTime()          
  57.         var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));  
  58.         var io = jQuery.createUploadIframe(id, s.secureuri);  
  59.         var frameId = 'jUploadFrame' + id;  
  60.         var formId = 'jUploadForm' + id;          
  61.         // Watch for a new set of requests  
  62.         if ( s.global && ! jQuery.active++ )  
  63.         {  
  64.             jQuery.event.trigger( "ajaxStart" );  
  65.         }              
  66.         var requestDone = false;  
  67.         // Create the request object  
  68.         var xml = {}     
  69.         if ( s.global )  
  70.             jQuery.event.trigger("ajaxSend", [xml, s]);  
  71.         // Wait for a response to come back  
  72.         var uploadCallback = function(isTimeout)  
  73.         {             
  74.             var io = document.getElementById(frameId);  
  75.             try   
  76.             {                 
  77.                 if(io.contentWindow)  
  78.                 {  
  79.                      xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;  
  80.                      xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;  
  81.                        
  82.                 }else if(io.contentDocument)  
  83.                 {  
  84.                      xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;  
  85.                     xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;  
  86.                 }                         
  87.             }catch(e)  
  88.             {  
  89.                 jQuery.handleError(s, xml, null, e);  
  90.             }  
  91.             if ( xml || isTimeout == "timeout")   
  92.             {                 
  93.                 requestDone = true;  
  94.                 var status;  
  95.                 try {  
  96.                     status = isTimeout != "timeout" ? "success" : "error";  
  97.                     // Make sure that the request was successful or notmodified  
  98.                     if ( status != "error" )  
  99.                     {  
  100.                         // process the data (runs the xml through httpData regardless of callback)  
  101.                         var data = jQuery.uploadHttpData( xml, s.dataType );      
  102.                         // If a local callback was specified, fire it and pass it the data  
  103.                         if ( s.success )  
  104.                             s.success( data, status );  
  105.       
  106.                         // Fire the global callback  
  107.                         if( s.global )  
  108.                             jQuery.event.trigger( "ajaxSuccess", [xml, s] );  
  109.                     } else  
  110.                         jQuery.handleError(s, xml, status);  
  111.                 } catch(e)   
  112.                 {  
  113.                     status = "error";  
  114.                     jQuery.handleError(s, xml, status, e);  
  115.                 }  
  116.   
  117.                 // The request was completed  
  118.                 if( s.global )  
  119.                     jQuery.event.trigger( "ajaxComplete", [xml, s] );  
  120.   
  121.                 // Handle the global AJAX counter  
  122.                 if ( s.global && ! --jQuery.active )  
  123.                     jQuery.event.trigger( "ajaxStop" );  
  124.   
  125.                 // Process result  
  126.                 if ( s.complete )  
  127.                     s.complete(xml, status);  
  128.   
  129.                 jQuery(io).unbind()  
  130.   
  131.                 setTimeout(function()  
  132.                                     {   try   
  133.                                         {  
  134.                                             jQuery(io).remove();  
  135.                                             jQuery(form).remove();    
  136.                                               
  137.                                         } catch(e)   
  138.                                         {  
  139.                                             jQuery.handleError(s, xml, null, e);  
  140.                                         }                                     
  141.   
  142.                                     }, 100)  
  143.   
  144.                 xml = null  
  145.   
  146.             }  
  147.         }  
  148.         // Timeout checker  
  149.         if ( s.timeout > 0 )   
  150.         {  
  151.             setTimeout(function(){  
  152.                 // Check to see if the request is still happening  
  153.                 if( !requestDone ) uploadCallback( "timeout" );  
  154.             }, s.timeout);  
  155.         }  
  156.         try   
  157.         {  
  158.   
  159.             var form = jQuery('#' + formId);  
  160.             jQuery(form).attr('action', s.url);  
  161.             jQuery(form).attr('method''POST');  
  162.             jQuery(form).attr('target', frameId);  
  163.             if(form.encoding)  
  164.             {  
  165.                 jQuery(form).attr('encoding''multipart/form-data');                 
  166.             }  
  167.             else  
  168.             {     
  169.                 jQuery(form).attr('enctype''multipart/form-data');              
  170.             }             
  171.             jQuery(form).submit();  
  172.   
  173.         } catch(e)   
  174.         {             
  175.             jQuery.handleError(s, xml, null, e);  
  176.         }  
  177.           
  178.         jQuery('#' + frameId).load(uploadCallback   );  
  179.         return {abort: function () {}};   
  180.   
  181.     },  
  182.   
  183.     uploadHttpData: function( r, type ) {  
  184.         var data = !type;  
  185.         data = type == "xml" || data ? r.responseXML : r.responseText;  
  186.         // If the type is "script", eval it in global context  
  187.         if ( type == "script" )  
  188.             jQuery.globalEval( data );  
  189.         // Get the JavaScript object, if JSON is used.  
  190.         if ( type == "json" )  
  191.             eval( "data = " + data );  
  192.         // evaluate scripts within html  
  193.         if ( type == "html" )  
  194.             jQuery("<div>").html(data).evalScripts();  
  195.   
  196.         return data;  
  197.     },  
  198.     handleError: function( s, xhr, status, e )      {  
  199.         // If a local callback was specified, fire it  
  200.                 if ( s.error ) {  
  201.                     s.error.call( s.context || s, xhr, status, e );  
  202.                 }  
  203.   
  204.                 // Fire the global callback  
  205.                 if ( s.global ) {  
  206.                     (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );  
  207.                 }  
  208.     }  
  209.    
  210. })  


注:如果出现

<strong><span style="color: rgb(255, 0, 0);">jQuery.handleError is not a function </span></strong>
<span style="color: rgb(51, 51, 51);">原因是,经测试handlerError只在jquery-1.4.2之前的版本中存在,jquery-1.6 和1.7中都没有这个函数了,因此在1.4.2中将这个函数复制到了ajaxFileUpload.js中,问题解决
handleError: function( s, xhr, status, e ) 		{
// If a local callback was specified, fire it
		if ( s.error ) {
			s.error.call( s.context || s, xhr, status, e );
		}

		// Fire the global callback
		if ( s.global ) {
			(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
		}
	},
问题2:一直得到error ,无法执行指定的success方法。通过追踪ajaxFileUpload的执行过程发现,在调用它自身的uploadHttpData函数时,当执行if(type=="json")    eval("data = "+data);
会抛出异常,导致在处理异常的时候将status = "error" 因此一直执行error方法。
上网查询,得知eval函数是用来执行一段js代码,而并不是如我所想的反解json串
eval("data = "+data);的意思是 将data 赋值给 data参数 ,但是当我返回给页面的是一个简单的字符串,比如"OK" ,时,这样写就抛出异常。最后改为 eval("data = \" "+data+" \" ");即将返回的数据用双引号引起来当作字符串,然后赋给 data 。终于成功了。。。
</span>



action:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1.        @RequestMapping(value = "/saveorupdate.jhtml")  
  2. @ResponseBody  
  3. public synchronized String saveOrUpdate(HttpServletRequest request) throws IOException {  
  4.     DynamicParams params = new DynamicParams(request);  
  5.     String projectId = request.getParameter("projectId");  
  6.     String name = request.getParameter("name");  
  7.     String type = request.getParameter("type");  
  8.     params.put("projectId", projectId);  
  9.     params.put("name", name);  
  10.     params.put("type", type);  
  11.   
  12.     MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
  13.     MultipartFile file = null;  
  14.     if("1".equals(type)){  
  15.         file = multipartRequest.getFile("file");// 获取上传文件名  
  16.     }else{  
  17.         file = multipartRequest.getFile("attachFile");// 获取上传文件名  
  18.     }  
  19.     ProjectPic projectPic = params.convertToEntity(ProjectPic.class);         
  20.     projectPicManager.save(projectPic, file.getInputStream());  
  21.     return successMsg();  
  22. }  

到此一切ok,开始上传文件吧!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值