ajaxFileUpload+SpringMVC框架+maven 实现文件上传

本文详细介绍了一个文件上传组件的实现过程,包括前端HTML页面设计、JavaScript交互逻辑、后端Controller处理逻辑及XML配置等内容。该组件支持文件上传并返回上传状态。

贴代码比较直接,要说明的是,网上下载的插件不能直接拿来用,要经过修改才能真正实现。


1、静态页面html端:

            <div>
                <label>信件主题:</label>
                <input id="title" name="title" type="text">
            </div>
            <div>
                <label><span>*</span>信件内容:</label>
                <textarea id="content" name="content" class="input"></textarea>
            </div>
            <div>
                <label>附  件:</label> 
                <input type="file" name="file" id="file" />   
            </div>
            <div>
                <button  type="submit" value="提交" onclick="mailbox_submit()">提交</button>
            </div>

2、js端:

function mailbox_submit(){
	var title=$.trim($("#title").val());
	var content=$.trim($("#content").val()); 
	$.ajaxFileUpload({
	        url: 'submit/upload.do',
	        type: 'post',
	        data : {		<pre name="code" class="html">                         title:title,
			 content:content 		 
}, secureuri: false, //一般设置为false fileElementId: 'file', // 上传文件的id、name属性名 dataType: 'json', success: function(data, status){ alert(data.status); }, error: function(data, status, e){ alert(e); } }); }

 

3、后端Controller代码:

@Controller
@RequestMapping("submit")
public class InteractController  extends BaseController{

	@Autowired
	private InteractService interactService;
 

	/**
	 * 用于内容新增/编辑时的ajax文件上传,将文件地址输出到页面
	 * 
	 * @return
	 */
	 
	 @RequestMapping("/upload"  )  
 	 @ResponseBody
	 public Map<String, Object> upload(Interact interact ,HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException {  
	    Map<String, Object> map = new HashMap<String, Object>();
	    String dateStr=DateUtil.getCurrentDate_String("YYYYMMDDHH24MISS");
	    //创建一个通用的多部分解析器  
	    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
	    //判断 request 是否有文件上传,即多部分请求  
	    if(multipartResolver.isMultipart(request)){  
	            //转换成多部分request    
	            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
	            //取得request中的所有文件名  
	            Iterator<String> iter = multiRequest.getFileNames();  
	            while(iter.hasNext()){  
	                //记录上传过程起始时的时间,用来计算上传时间  
	                int pre = (int) System.currentTimeMillis();  
	                //取得上传文件  
	                MultipartFile file = multiRequest.getFile(iter.next());  
	                if(file != null){  
	                    //取得当前上传文件的文件名称  
	                    String myFileName = file.getOriginalFilename();  
	                    //如果名称不为“”,说明该文件存在,否则说明该文件不存在  
	                    if(myFileName.trim() !=""){
		                    	System.out.println(myFileName);  
		                        //重命名上传后的文件名  
		                        String fileName = "demoUpload" + file.getOriginalFilename();  
		                        //定义上传路径  
		                        String path = "D:/" + fileName;  
		                        File localFile = new File(path);  
		                        file.transferTo(localFile); 
		                	interact.setFileid(dateStr);//文件号  可能会将这个提供给用户 作为查询编号
		                	interact.setXjfileid(dateStr);
		                        interact.setXjname(myFileName);//信件原文件名称(中文.doc)
		                        interact.setXjsuffix(getExtensionName(myFileName));//文件后缀名
		                        interact.setXjnamesave(dateStr+"."+getExtensionName(myFileName));//信件存储文件名称(201234758454.doc)
		                        interact.setXjpath("upload/web");
		                        map.put("status", "success");
	                    }  
	                }   
	            }  
	        } 
	        return map;
	    }  
	 
	 /*
	  * Java文件操作 获取文件扩展名
	  *
	  */
	     public static String getExtensionName(String filename) { 
	         if ((filename != null) && (filename.length() > 0)) { 
	             int dot = filename.lastIndexOf('.'); 
	             if ((dot >-1) && (dot < (filename.length() - 1))) { 
	                 return filename.substring(dot + 1); 
	             } 
	         } 
	         return filename; 
	     } 

	@Resource
	public void setInteractService(InteractService interactService) {
		this.interactService = interactService;
	}
}

4、xml配置文件端:


<!-- 支持上传文件 -->  
     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="defaultEncoding" value="utf-8"></property>   
        <property name="maxUploadSize" value="10485760000"></property>  
        <property name="maxInMemorySize" value="40960"></property>  
     </bean> 

5、这份插件代码应该是最重要的,有点长,可以全部复制:

jQuery.extend({  
    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, data)  
    {  
        //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);  
          
        //增加文本参数的支持  
        if (data) {  
            for (var i in data) {  
                $('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').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 = new Date().getTime()          
        var form = jQuery.createUploadForm(id, s.fileElementId, s.data);  
        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);  
        //    alert("ww");
            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;  
         //       alert("eee");
                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 )   
        {  
        //	alert("timeout")
            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);  
        }  
   //     alert(document.getElementById(frameId));
        if(window.attachEvent){  
            document.getElementById(frameId).attachEvent('uploadCallback');  
        }  
        else{  
            document.getElementById(frameId).addEventListener('load', uploadCallback, false);  
        }         
        return {abort: function () {}};   
  
    },  
  
    uploadHttpData: function( r, type ) {  
   // 	alert("uploadHttpData");
        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" )  
        	data = r.responseText;  
        var start = data.indexOf(">");  
        if(start != -1) {  
          var end = data.indexOf("<", start + 1);  
          if(end != -1) {  
            data = data.substring(start + 1, end);  
           }  
        } 
            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;  
    }  
})

6、修改该插件源码的博客出处: http://cnn237111.blog.51cto.com/2359144/505739

7、还有一个出处: 后期补上。代码真是各处整合.. 希望这份代码对你有帮助。

 






 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值