jQuery没有提供ajax的文件上传,我们可以通过ajaxfileupload实现ajax文件的上传。其实ajaxfileupload文件上传特别的简单。下面就演示一下在SpringMVC中实现ajax的文件上传。

      1、后台接收代码

     首先在spring的配置文件中添加文件上传配置

     

<!-- 文件上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"/> </bean>    再写文件接收的代码

  1 package com.chinaunicom.jlmssp.controller;
  2 
  3 import java.io.File;
  4 import java.io.IOException;
  5 import java.util.Arrays;
  6 import java.util.Date;
  7 import java.util.HashMap;
  8 
  9 import javax.servlet.ServletContext;
 10 import javax.servlet.http.HttpServletRequest;
 11 import javax.servlet.http.HttpServletResponse;
 12 import javax.servlet.http.HttpSession;
 13 
 14 import org.apache.commons.fileupload.servlet.ServletFileUpload;
 15 import org.springframework.beans.factory.annotation.Autowired;
 16 import org.springframework.stereotype.Controller;
 17 import org.springframework.ui.Model;
 18 import org.springframework.web.bind.annotation.RequestMapping;
 19 import org.springframework.web.bind.annotation.RequestMethod;
 20 import org.springframework.web.bind.annotation.RequestParam;
 21 import org.springframework.web.bind.annotation.ResponseBody;
 22 import org.springframework.web.multipart.commons.CommonsMultipartFile;
 23 
 24 import com.chinaunicom.jlmssp.model.DataResponse;
 25 import com.chinaunicom.jlmssp.model.JavaToJsMsg;
 26 import com.chinaunicom.jlmssp.model.Org_UserInfo;
 27 import com.chinaunicom.jlmssp.model.Repaly_Expert_Home_Page;
 28 import com.chinaunicom.jlmssp.services.Replay_ExpertManageService;
 29 
 30 /**
 31  * 项目复制管理子系统
 32  * 专家云管理
 33  * @author SunYue
 34  * @version 0.1
 35  */
 36 @Controller
 37 @RequestMapping("/admin/Replay_ExpertManageController.do")
 38 public class Replay_ExpertManageController {
 39    
 40     private static final HashMap<String, String> TypeMap = new HashMap<String, String>();
 41 
 42     static {
 43         TypeMap.put("image", "gif,jpg,jpeg,png,bmp");
 44         TypeMap.put("flash", "swf,flv");
 45         TypeMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
 46         TypeMap.put("file", "doc,docx,xls,xlsx,ppt,pptx,htm,html,txt,dwg,pdf");
 47     }
 48 
 49 
 50     @Autowired
 51     Replay_ExpertManageService replayExpertManageService;
 52        
 53         /**
 54          * @author sunyue
 55          * @date 2017年2月28日 下午12:49:33
 56          * @Description: 图片上传方法
 57          * @return message: -1 没有文件上传 0 上传成功 1 上传失败 2 文件超过上传大小 3 文件格式错误 4 上传文件路径非法 5 上传目录没有写权限
 58          * @return void 返回类型
 59          */
 60         @RequestMapping(params = "op=getImageUpload", method = RequestMethod.POST)
 61         public void  getImageUpload(@RequestParam("upload") CommonsMultipartFile file,HttpServletRequest request,
 62                 HttpServletResponse response) {
 63             if (!file.isEmpty()) {
 64                 /*ServletContext servletContext = request.getSession()
 65                         .getServletContext();
 66                 String uploadPath = servletContext.getRealPath("/")
 67                         + "images\\replay-expert\\";
 68                
 69                 String upPathString  = request.getServletPath(); */
 70                
 71                 //获取项目工作空间下工程路径的方法,将图片保存到工程路径下
 72                 String t=Thread.currentThread().getContextClassLoader().getResource("").getPath();
 73                  int num=t.indexOf(".metadata");
 74                  String uploadPath=t.substring(1,num).replace('/', '\\')+"jl_mssp_V3_0\\WebContent\\images\\replay-expert\\";
 75                
 76                 // 文件上传大小
 77                 long fileSize = 3 * 1024 * 1024;
 78 
 79                 if (file.getSize() > fileSize) {
 80                     backInfo(response, false, 2, "");
 81                     return;
 82                 }
 83 
 84                 String OriginalFilename = file.getOriginalFilename();
 85 
 86                 String fileSuffix = OriginalFilename.substring(
 87                         OriginalFilename.lastIndexOf(".") + 1).toLowerCase();
 88                 if (!Arrays.asList(TypeMap.get("image").split(",")).contains(
 89                         fileSuffix)) {
 90                     backInfo(response, false, 3, "");
 91                     return;
 92                 }
 93 
 94                 if (!ServletFileUpload.isMultipartContent(request)) {
 95                     backInfo(response, false, -1, "");
 96                     return;
 97                 }
 98 
 99                 // 检查上传文件的目录
100                 File uploadDir = new File(uploadPath);
101                 if (!uploadDir.isDirectory()) {
102                     if (!uploadDir.mkdir()) {
103                         backInfo(response, false, 4, "");
104                         return;
105                     }
106                 }
107 
108                 // 是否有上传的权限
109                 if (!uploadDir.canWrite()) {
110                     backInfo(response, false, 5, "");
111                     return;
112                 }
113                
114                 //新文件名
115                 String newname = "";
116                 /*if(null != filePre){
117                     newname += filePre;//对应模块上传的文件名前缀
118                 }*/
119                
120                  newname +=    "test1111" + "." + fileSuffix;
121 
122                 File saveFile = new File(uploadPath, newname);
123 
124                 try {
125                     file.transferTo(saveFile);
126                     backInfo(response, true, 0, newname);
127                 } catch (Exception e) {
128                     //LOG.error(e.getMessage(), e);
129                     backInfo(response, false, 1, "");
130                     return;
131                 }
132             } else {
133                 backInfo(response, false, -1, "");
134                 return;
135             }
136         }
137        
138         // 返回信息
139         private void backInfo(HttpServletResponse response, boolean flag, int message,
140                 String fileName) {
141             String json  = "";
142             if (flag) {
143                 json = "{ \"status\": \"success";
144             } else {
145                 json = "{ \"status\": \"error";
146             }
147             json += "\",\"fileName\": \"" + fileName + "\",\"message\": \"" + message + "\"}";
148             try {
149                 response.setContentType("text/html;charset=utf-8");
150                 response.getWriter().write(json);
151             } catch (IOException e) {
152                 //LOG.error(e.getMessage(), e);
153             }
154         }
155 }

  2、前台接受代码

          使用ajaxfileupload时,首先下载ajaxfileupload文件,导入对应的js文件

    

<script type="text/javascript" src="js/ajaxfileupload.js"></script>

       文件传输字段必须为file类型,如下:

 

<input type="file" id="file" name="file" onchange="ajaxFileUpload();"/>


      其次,处理上传文件:

 1 function ajaxFileUpload() {
 2     $.ajaxFileUpload({
 3         type: "POST",
 4         async: false,
 5         data: { "op": 'getImageUpload'},
 6         url:"Replay_ExpertManageController.do",
 7         dataType: 'json',
 8         secureuri: false,
 9         fileElementId: "upload",
10         success: function(data, status) {
11             if (data.status == "success") {
12                 //上传成功
13                 alert("上传照片成功");
14             }
15             switch(data.message){
16              //解析上传状态
17                 case "0" : //上传成功
18                            break;
19                 case "-1" : //上传文件不能为空
20                           break;
21                 default: //上传失败
22                      break;
23             }
24             return false;
25         }/* ,
26         error :  function (jqXHR, textStatus, errorThrown) {
27             //弹出jqXHR对象的信息
28             alert(jqXHR.responseText);
29             //alert(jqXHR.status);
30             //alert(jqXHR.readyState);
31             //alert(jqXHR.statusText);
32                //弹出其他两个参数的信息
33             //alert(textStatus);
34             alert(errorThrown);
35             return false;
36         } */
37     });
38 }

 

三、由于网上的ajaxuploadfile文件都是高版本的,这里将改版完全版文件传上,自己使用

 

  1 jQuery.extend({
  2     handleError: function( s, xhr, status, e )         {
  3         // If a local callback was specified, fire it
  4                 if ( s.error ) {
  5                     s.error.call( s.context || s, xhr, status, e );
  6                 }
  7 
  8                 // Fire the global callback
  9                 if ( s.global ) {
 10                     (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
 11                 }
 12     },
 13     createUploadIframe: function(id, uri)
 14     {
 15  
 16         var frameId = 'jUploadFrame' + id;
 17        
 18         if(window.ActiveXObject) {
 19             if(jQuery.browser.version=="9.0")
 20             {
 21                 io = document.createElement('iframe');
 22                 io.id = frameId;
 23                 io.name = frameId;
 24             }
 25             else if(jQuery.browser.version=="6.0" || jQuery.browser.version=="7.0" || jQuery.browser.version=="8.0")
 26             {
 27            
 28                 var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
 29                 if(typeof uri== 'boolean'){
 30                     io.src = 'javascript:false';
 31                 }
 32                 else if(typeof uri== 'string'){
 33                     io.src = uri;
 34                 }
 35             }
 36         }
 37         else {
 38             var io = document.createElement('iframe');
 39             io.id = frameId;
 40             io.name = frameId;
 41         }
 42         io.style.position = 'absolute';
 43         io.style.top = '-1000px';
 44         io.style.left = '-1000px';
 45 
 46         document.body.appendChild(io);
 47 
 48         return io;       
 49     },
 50     ajaxUpload:function(s,xml){
 51         //if((fromFiles.nodeType&&!((fileList=fromFiles.files)&&fileList[0].name)))
 52 
 53         var uid = new Date().getTime(),idIO='jUploadFrame'+uid,_this=this;
 54         var jIO=$('<iframe name="'+idIO+'" id="'+idIO+'" style="display:none">').appendTo('body');
 55         var jForm=$('<form action="'+s.url+'" target="'+idIO+'" method="post" enctype="multipart/form-data"></form>').appendTo('body');
 56         var oldElement = $('#'+s.fileElementId);
 57         var newElement = $(oldElement).clone();
 58         $(oldElement).attr('id', 'jUploadFile'+uid);
 59         $(oldElement).before(newElement);
 60         $(oldElement).appendTo(jForm);
 61 
 62         this.remove=function()
 63         {
 64             if(_this!==null)
 65             {
 66                 jNewFile.before(jOldFile).remove();
 67                 jIO.remove();jForm.remove();
 68                 _this=null;
 69             }
 70         }
 71         this.onLoad=function(){
 72        
 73             var data=$(jIO[0].contentWindow.document.body).text();
 74    
 75    
 76             try{
 77 
 78                 if(data!=undefined){
 79                     data = eval('(' + data + ')');
 80                     try {
 81                        
 82                         if (s.success)
 83                             s.success(data, status);
 84    
 85                         // Fire the global callback
 86                         if(s.global)
 87                             jQuery.event.trigger("ajaxSuccess", [xml, s]);
 88                         if (s.complete)
 89                             s.complete(data, status);
 90                         xml = null;
 91                       } catch(e)
 92                          {
 93                     
 94                         status = "error";
 95                         jQuery.handleError(s, xml, status, e);
 96                       }
 97 
 98                       // The request was completed
 99                       if(s.global)
100                           jQuery.event.trigger( "ajaxComplete", [xml, s] );
101                       // Handle the global AJAX counter
102                       if (s.global && ! --jQuery.active )
103                           jQuery.event.trigger("ajaxStop");
104 
105                       // Process result
106       
107                 }
108          }catch(ex){
109               alert(ex.message);
110          };
111         }
112         this.start=function(){jForm.submit();jIO.load(_this.onLoad);};
113         return this;
114          
115     },
116     createUploadForm: function(id, url,fileElementId, data)
117     {
118         //create form   
119         var formId = 'jUploadForm' + id;
120         var fileId = 'jUploadFile' + id;
121         var form = jQuery('<form  action="'+url+'" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');   
122         if(data)
123         {
124             for(var i in data)
125             {
126                 jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
127             }           
128         }   
129 
130         var oldElement = jQuery('#' + fileElementId);
131         var newElement = jQuery(oldElement).clone();
132         jQuery(oldElement).attr('id', fileId);
133         jQuery(oldElement).before(newElement);
134         jQuery(oldElement).appendTo(form);
135 
136         //set attributes
137         jQuery(form).css('position', 'absolute');
138         jQuery(form).css('top', '-1200px');
139         jQuery(form).css('left', '-1200px');
140         jQuery(form).appendTo('body');       
141         return form;
142     },
143     ajaxFileUpload: function(s) {
144         // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout   
145         // Create the request object
146         var xml = {};
147         s = jQuery.extend({}, jQuery.ajaxSettings, s);
148         if(window.ActiveXObject){
149             var upload =  new jQuery.ajaxUpload(s,xml);
150             upload.start();
151          
152        }else{
153         var id = new Date().getTime();
154         var form = jQuery.createUploadForm(id,s.url, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
155         var io = jQuery.createUploadIframe(id, s.secureuri);
156         var frameId = 'jUploadFrame' + id;
157         var formId = 'jUploadForm' + id;       
158         // Watch for a new set of requests
159         if ( s.global && ! jQuery.active++ )
160         {
161             jQuery.event.trigger( "ajaxStart" );
162         }           
163         var requestDone = false;
164     
165         if ( s.global )
166             jQuery.event.trigger("ajaxSend", [xml, s]);
167         // Wait for a response to come back
168         var uploadCallback = function(isTimeout)
169         {           
170             var io = document.getElementById(frameId);
171    
172             try
173             {               
174                 if(io.contentWindow)
175                 {
176                      xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
177                      xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
178                      
179                 }else if(io.contentDocument)
180                 {
181                      xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
182                      xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
183                 }                       
184             }catch(e)
185             {
186                 jQuery.handleError(s, xml, null, e);
187             }
188             if ( xml || isTimeout == "timeout")
189             {               
190                 requestDone = true;
191                 var status;
192                 try {
193                     status = isTimeout != "timeout" ? "success" : "error";
194                     // Make sure that the request was successful or notmodified
195                     if ( status != "error" )
196                     {
197                         // process the data (runs the xml through httpData regardless of callback)
198                         var data = jQuery.uploadHttpData(xml, s.dataType);   
199                         // If a local callback was specified, fire it and pass it the data
200             
201                         if (s.success)
202                             s.success(data, status);
203    
204                         // Fire the global callback
205                         if(s.global)
206                             jQuery.event.trigger("ajaxSuccess", [xml, s]);
207                         if (s.complete)
208                             s.complete(data, status);
209                        
210                     } else
211                         jQuery.handleError(s, xml, status);
212                 } catch(e)
213                 {
214                     status = "error";
215                     jQuery.handleError(s, xml, status, e);
216                 }
217 
218                 // The request was completed
219                 if(s.global)
220                     jQuery.event.trigger( "ajaxComplete", [xml, s] );
221                 // Handle the global AJAX counter
222                 if (s.global && ! --jQuery.active )
223                     jQuery.event.trigger("ajaxStop");
224 
225                 // Process result
226                 jQuery(io).unbind();
227 
228                 setTimeout(function()
229                                     {    try
230                                         {
231                                             jQuery(io).remove();
232                                             jQuery(form).remove();   
233                                            
234                                         } catch(e)
235                                         {
236                                             jQuery.handleError(s, xml, null, e);
237                                         }                                   
238 
239                                     }, 100);
240 
241                 xml = null;
242 
243             }
244         };
245         // Timeout checker
246         if (s.timeout>0)
247         {
248             setTimeout(function(){
249                 // Check to see if the request is still happening
250                 if( !requestDone ) uploadCallback("timeout");
251             }, s.timeout);
252         }
253      
254             try
255                 {
256        
257                     var form = jQuery('#' + formId);
258                     jQuery(form).attr('action', s.url);
259                     jQuery(form).attr('method', 'POST');
260                     jQuery(form).attr('target', frameId);
261                    
262                     if(form.encoding)
263                     {
264                         jQuery(form).attr('encoding', 'multipart/form-data');                 
265                     }
266                     else
267                     {   
268                         jQuery(form).attr('enctype', 'multipart/form-data');           
269                     }   
270           
271                    
272                     jQuery(form).submit();
273        
274                 } catch(e)
275                 {   
276                     jQuery.handleError(s, xml, null, e);
277                 }
278                
279                 jQuery('#'+ frameId).load(uploadCallback);
280                 return {abort: function () {}};   
281  
282        }
283     },
284 
285     uploadHttpData: function( r, type ) {
286        
287         var data = !type;
288         data = type == "xml" || data ? r.responseXML : r.responseText;
289         // If the type is "script", eval it in global context
290         if ( type == "script" )
291             jQuery.globalEval( data );
292         // Get the JavaScript object, if JSON is used.
293         if ( type == "json" ){
294   
295             eval( "data = " + $(data).html() );
296         }
297         // evaluate scripts within html
298         if ( type == "html" )
299             jQuery("<div>").html(data).evalScripts();
300  
301         return data;
302     }
303 });

 

posted on 2017-04-19 15:03  书未来  阅读(505)  评论(0编辑  收藏  举报