• springMvc 使用ajax上传文件,返回获取的文件数据 附Struts2文件上传


    总结一下 springMvc使用ajax文件上传

    首先说明一下,以下代码所解决的问题 :前端通过input file 标签获取文件,通过ajax与后端交互,后端获取文件,读取excel文件内容,返回excel文件内容给前端并显示。

    难点主要在于controller如何或得前端传递过来的文件,或者文件流

    前端引用 :ajaxfileupload.js

    ajaxfileupload.js 代码:

    jQuery.extend({
    	//扩展函数
    	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] );
    		}
    	},
    	
        createUploadIframe: function(id, uri)
    	{
    			//create frame
                var frameId = 'jUploadFrame' + id;
                var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
    			if(window.ActiveXObject)
    			{
                    if(typeof uri== 'boolean'){
    					iframeHtml += ' src="' + 'javascript:false' + '"';
    
                    }
                    else if(typeof uri== 'string'){
    					iframeHtml += ' src="' + uri + '"';
    
                    }	
    			}
    			iframeHtml += ' />';
    			jQuery(iframeHtml).appendTo(document.body);
    
                return jQuery('#' + frameId).get(0);			
        },
        
        createUploadForm: function(id, fileElementId, data)
    	{
    		//create form	
    		var formId = 'jUploadForm' + id;
    		var fileId = 'jUploadFile' + id;
    		var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');	
    		if(data)
    		{
    			for(var i in data)
    			{
    				jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
    			}			
    		}		
    		var oldElement = jQuery('#' + fileElementId);
    		var newElement = jQuery(oldElement).clone();
    		jQuery(oldElement).attr('id', fileId);
    		jQuery(oldElement).before(newElement);
    		jQuery(oldElement).appendTo(form);
    
    
    		
    		//set attributes
    		jQuery(form).css('position', 'absolute');
    		jQuery(form).css('top', '-1200px');
    		jQuery(form).css('left', '-1200px');
    		jQuery(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, (typeof(s.data)=='undefined'?false: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);
                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 
    										{
    											jQuery(io).remove();
    											jQuery(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 form = jQuery('#' + formId);
    			jQuery(form).attr('action', s.url);
    			jQuery(form).attr('method', 'POST');
    			jQuery(form).attr('target', frameId);
                if(form.encoding)
    			{
    				jQuery(form).attr('encoding', 'multipart/form-data');      			
                }
                else
    			{	
    				jQuery(form).attr('enctype', 'multipart/form-data');			
                }			
                jQuery(form).submit();
    
            } catch(e) 
    		{			
                jQuery.handleError(s, xml, null, e);
            }
    		
    		jQuery('#' + frameId).load(uploadCallback	);
            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" )
                eval( "data = " + data );
            // evaluate scripts within html
            if ( type == "html" )
                jQuery("<div>").html(data).evalScripts();
            
            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 );  
            	}  
            return data;
        }
        
    });
    

    html代码:

    1 <div id="fileUpLoad" class="manage">  
    2                  <div style="display: none;">
    3                      <input type="file" id="btnFile" name="btnFile" />  
    4                  </div>
    5                      <input type="text" id="txtFoo" readonly="readonly" style="300px" />           
    6                      <button onclick="btnFile.click()" style="height: 25px;">选择文件</button>
    7 </div>

    javaScript代码:

    <script>
    function confirm(){
    
        var fileName = $("#btnFile").val();//文件名
        fileName = fileName.split("\");
        fileName = fileName[fileName.length-1];
        jQuery.ajaxSettings.traditional = true;  
        $.ajaxFileUpload({  
            url : '${pageContext.request.contextPath }/plan/fileUpLoads.do',  
            secureuri : false,//安全协议  
            fileElementId:'btnFile',//id  
            type : 'POST',  
            dataType : 'text',  
            error : function(data) {  
                
            },  
            success : function(data) { 
                
                var start = data.indexOf("[");  
                var end = data.indexOf("]");  
                var jsonStr = data.substring(start,end+1);  
                var foreach = "{'row':"+jsonStr+"}";
                var json = eval("("+foreach+")");
               
                ty="";
                       jQuery.each(json.row, function(i,item){ 
                           
                          var _len = item.operation;
                       ty +="<tr class='lay0 taskTitle' id="+_len+" align='center'>"
                       +"<td style='text-align:center'>"+_len+"</td>"
                       +"<input type='hidden' name='num_"+_len+"' value="+_len+" /><input type='hidden' name='planid_"+_len+"' value='' />"
                       +"<td><input type='text' size=25 name='title_"+_len+"' value='"+item.eventnode+"'  id='desc"+_len+"' /></td>"
                       +"<td><input type='text' size=30 name='method_"+_len+"' id='method"+_len+"' value='"+item.workplan+"'/></td>"
                       +"<td><input type='text' size=25 name='steps_"+_len+"' id='steps"+_len+"' value='"+item.chengguomiaoshu+"'/></td>"
                       +"<td><input type='text' size=12 name='time_"+_len+"' value='"+item.completetime+"'  id='time"+_len+"' onClick='WdatePicker()'/></td>"
                       +"<td> <input type='text' size=14 name='leader_name"+_len+"' wrap='yes' readonly value='"+item.person+"' ><a href='javascript:;' class='orgAdd'>添加</a>&nbsp;&nbsp;<a href='javascript:;' class='orgdel'>清空</a></td>"
                       +"<td><a href='javascript:void(0);' onclick='addchild("+_len+")'>添加节点</a><br/><a href='javascript:void(0);' onclick='deltr("+_len+")'>删除节点</a></td>"
                       +"</tr>";
                       
                  });
                $("#taskContent").append(ty); 
            }  
        });  
        
        
        $('.myModal1,.mask').hide();
    }
    
    
    </script>

    这里ajax 的 dataType : 'text',如果这里是json类型就会接不到ajax返回的数据

    success : function(data) {}这里的data 是 ajax成功后数据,因为dataType:'text'的缘故,这里的data并不是json数据,也不可直接使用,上述success方法里的 

    var start = data.indexOf("[");  
    var end = data.indexOf("]");  
    var jsonStr = data.substring(start,end+1);  
    var foreach = "{'row':"+jsonStr+"}";
    var json = eval("("+foreach+")");
    就是将data转化为json格式

    controller代码:
     1 //btnFile对应页面的name属性  
     2     @RequestMapping("/fileUpLoads")
     3     public @ResponseBody List<OnlineAddplanWithBLOBs> fileUpLoad(@RequestParam MultipartFile[] btnFile, HttpServletRequest request, HttpServletResponse response){  
     4         5         List<OnlineAddplanWithBLOBs> list = new ArrayList<OnlineAddplanWithBLOBs>();
     6         InputStream is;
     7         try {
     8             //文件类型:btnFile[0].getContentType()  
     9             //文件名称:btnFile[0].getName()
    10             is = btnFile[0].getInputStream();//多文件也适用,我这里就一个文件  
    11           
    12             POIFSFileSystem fs = new POIFSFileSystem(is);
    13             
    14             HSSFWorkbook wb=new HSSFWorkbook(fs);
    15             HSSFSheet hssfSheet=wb.getSheetAt(0);  // 获取第一个Sheet页
    16             if(hssfSheet!=null){
    17                 for(int rowNum=1;rowNum<=hssfSheet.getLastRowNum();rowNum++){
    18                     HSSFRow hssfRow=hssfSheet.getRow(rowNum);
    19                     if(hssfRow==null){
    20                         continue;
    21                     }else{
    22                         OnlineAddplanWithBLOBs bean = new OnlineAddplanWithBLOBs();
    23                         bean.setOperation(ExcelUtil.formatCell(hssfRow.getCell(0)));
    24                         bean.setEventnode(ExcelUtil.formatCell(hssfRow.getCell(1)));
    25                         bean.setWorkplan(ExcelUtil.formatCell(hssfRow.getCell(2)));
    26                         bean.setChengguomiaoshu(ExcelUtil.formatCell(hssfRow.getCell(3)));
    27                         bean.setCompletetime(ExcelUtil.formatCell(hssfRow.getCell(4)));
    28                         bean.setPerson(ExcelUtil.formatCell(hssfRow.getCell(5)));
    29                         System.out.println("序号是 "+bean.getOperation());
    30                         System.out.println("事项节点是 "+bean.getEventnode());
    31                         System.out.println("工作思路是 "+bean.getWorkplan());
    32                         System.out.println("成果描述是 "+bean.getChengguomiaoshu());
    33                         if(!"".equals(bean.getEventnode())){
    34                             System.out.println("=========== 有添加数据 ");
    35                             list.add(bean);
    36                         }
    37                     }
    38                 }
    39               }
    40             } catch (IOException e) {
    41                 e.printStackTrace();
    42             }
    43 44        45         return list;
    46     }

    这里是controller的代码 核心代码就是读取excel文件流
    InputStream is = btnFile[0].getInputStream();//获取excel文件输入流
    POIFSFileSystem fs = new
    POIFSFileSystem(is);
    HSSFWorkbook wb=new HSSFWorkbook(fs);
    HSSFSheet hssfSheet=wb.getSheetAt(0);
    HSSFRow hssfRow=hssfSheet.getRow(rowNum);

    ExcelUtil.formatCell()这个方法是将获取单元格的内容转换成字符串
     1 public static String formatCell(HSSFCell hssfCell){
     2         if(hssfCell==null){
     3             return "";
     4         }else{
     5             if(hssfCell.getCellType()==HSSFCell.CELL_TYPE_BOOLEAN){
     6                 return String.valueOf(hssfCell.getBooleanCellValue());
     7             }else if(hssfCell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){
     8                 return String.valueOf(hssfCell.getNumericCellValue());
     9             }else{
    10                 return String.valueOf(hssfCell.getStringCellValue());
    11             }
    12         }
    13     }
    
    
    struts2文件上传

      html代码:
     1 <form id="uploadForm" action="user!upload" method="post" enctype="multipart/form-data">
     2             <table>
     3                 <tr>
     4                     <td>下载模版:</td>
     5                     <td><a href="javascript:void(0)" class="easyui-linkbutton"  onclick="downloadTemplate()">导入模版</a></td>
     6                 </tr>
     7                 <tr>
     8                     <td>上传文件:</td>
     9                     <td><input type="file" name="userUploadFile"></td>
    10                 </tr>
    11             </table>
    12 </form>

      action代码

     1 private File userUploadFile;
     2 
     3 public File getUserUploadFile() {
     4     return userUploadFile;
     5 }
     6 public void setUserUploadFile(File userUploadFile) {
     7     this.userUploadFile = userUploadFile;
     8 }
     9 
    10 public String upload()throws Exception{
    11         POIFSFileSystem fs=new POIFSFileSystem(new FileInputStream(userUploadFile));
    12         HSSFWorkbook wb=new HSSFWorkbook(fs);
    13         HSSFSheet hssfSheet=wb.getSheetAt(0);  // 获取第一个Sheet页
    14         if(hssfSheet!=null){
    15             for(int rowNum=1;rowNum<=hssfSheet.getLastRowNum();rowNum++){
    16                 HSSFRow hssfRow=hssfSheet.getRow(rowNum);
    17                 if(hssfRow==null){
    18                     continue;
    19                 }
    20                 User user=new User();
    21                 user.setName(ExcelUtil.formatCell(hssfRow.getCell(0)));
    22                 user.setPhone(ExcelUtil.formatCell(hssfRow.getCell(1)));
    23                 user.setEmail(ExcelUtil.formatCell(hssfRow.getCell(2)));
    24                 user.setQq(ExcelUtil.formatCell(hssfRow.getCell(3)));
    25                 
    26             }
    27         }
    28         
    29         return null;
    30     }
    31     

      struts.xml 直接配置一下映射就可以了

    
    
     
  • 相关阅读:
    在博客园里给图片加水印(canvas + drag)
    Chrome开发者工具使用指南
    《古剑奇谭3》千秋戏辅助工具(前端React制作)
    React中useEffect的源码解读
    关于为什么使用React新特性Hook的一些实践与浅见
    使用@babel/preset-typescript取代awesome-typescript-loader和ts-loader
    使用dva改造React旧项目的数据流方案
    在React旧项目中安装并使用TypeScript的实践
    安利一个绘制指引线的JS库leader-line
    微信小程序中悬浮窗功能的实现(主要探讨和解决在原生组件上的拖动)
  • 原文地址:https://www.cnblogs.com/cmyxn/p/6230789.html
Copyright © 2020-2023  润新知