1. 程式人生 > >springmvc+mybatis批量上傳檔案

springmvc+mybatis批量上傳檔案

1:引入ajaxfileupload.js

<span style="font-size:12px;"><span style="font-size:12px;">// JavaScript Document
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)
 {
  //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>'); 
  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 = s.fileElementId;        
  var form = jQuery.createUploadForm(id, s.fileElementId);
  var io = jQuery.createUploadIframe(id, s.secureuri);
  var frameId = 'jUploadFrame' + id;
  var formId = 'jUploadForm' + id;  
        
        if( s.global && ! jQuery.active++ )
  {
   // Watch for a new set of requests
   jQuery.event.trigger( "ajaxStart" );
  }            
        var requestDone = false;
        // Create the request object
        var xml = {};   
        if( s.global )
        {
         jQuery.event.trigger("ajaxSend", [xml, s]);
        }            
        
        var uploadCallback = function(isTimeout)
  {  
   // Wait for a response to come back 
   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( s.success )
                        {
       // ifa local callback was specified, fire it and pass it the data
                         s.success( data, status );
                        };                 
                        if( s.global )
                        {
       // Fire the global callback
                         jQuery.event.trigger( "ajaxSuccess", [xml, s] );
                        };                            
                    } else
                    {
                     jQuery.handleError(s, xml, status);
                    }
                        
                } catch(e) 
    {
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                };                
                if( s.global )
                {
     // The request was completed
                 jQuery.event.trigger( "ajaxComplete", [xml, s] );
                };
                    

                // Handle the global AJAX counter
                if(s.global && ! --jQuery.active)
                {
                 jQuery.event.trigger("ajaxStop");
                };
                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(){
                
                if( !requestDone )
                {
     // Check to see ifthe request is still happening
                 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)
   {
                form.encoding = 'multipart/form-data';    
            }
            else
   {    
                form.enctype = 'multipart/form-data';
            }   
            jQuery(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;
        // ifthe type is "script", eval it in global context
        if( type == "script" )
        {
         jQuery.globalEval( data );
        }
            
        // Get the JavaScript object, ifJSON is used.
        if( type == "json" )
        {
         eval( "data = " + data );
        }
            
        // evaluate scripts within html
        if( type == "html" )
        {
         jQuery("<div>").html(data).evalScripts();
        }
            
        return data;
    },
    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;
    }
});
</span></span>
2:jsp程式碼
<span style="font-size:12px;"><%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> 
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<title></title>
<meta name="keywords" content="">
<meta name="description" content="">
<meta name="author" content="">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="">
</head>
<script src="<%=request.getContextPath()%>/man/js/ajaxfileupload.js"></script>
<%@ include file="/WEB-INF/views/treeogrist.jsp"%>
<script type="text/javascript">

var url = getContextPath()+'/czevent/sendFile.html';
function sendFile(){
	var excelFile  =$("#file_upload").val();
	
    if(excelFile =='') {
    layer.alert("請選擇需上傳的檔案!");
    return false;
    } 

    if(excelFile .indexOf('.xls')==-1){
    	layer.alert("檔案格式不正確,請選擇正確的Excel檔案(字尾名.xls)!");
    	return false;
    }
    $.ajaxFileUpload({
        url:url,//處理圖片指令碼
        secureuri :false,
        fileElementId :'file_upload',//file控制元件id
        type:"POST",
		dataType:"json",
		async : true,
		data:{},
        success : function (data,status){
        	 if(data.error=='0'){
        		 layer.alert('產值事件批量匯入成功', {icon: 1});
        		 laypageInitCZEventList();
        		 limt();
        	 }else{
        		 layer.alert(data.message,{icon:2});
        	 }
        	 
        },
        });
}
$(function () {
    $('#btn').click(function(){
	$('#file_upload').click();
    });
}); 
</script>
<body >
            <div class="page005">
                <div class="row">
                    <div class="col-xs-3">
                        <div class="panel">
                            <div class="panel-body">
                                <div class="tree structure-left structure-dept">
                                    <div id="jsTree_cztype" class="demo jstree jstree-2 jstree-default jstree-default-responsive" role="tree"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-xs-9">
                        <div class="panel panel-ui">
                            <div class="panel-heading">
                                <form class="form-inline">
                                    <div class="form-group">
                                        <a href="javascript:;" onclick="jkManage.export();" class="export action">事件匯出</a>
                                        <a href="javascript:;" id='btn' class="import action" >事件匯入</a>
                                        <input id="file_upload"  name="file_upload" type="file" onchange="sendFile()"  style='display:none;'>
                                        <a href="<%=request.getContextPath()%>/download/excel.html?fileName=下載模板.xls" target=" _blank" class="download action">下載事件模板</a>
                                    </div>
                                </form>
                            </div>
                            <div class="panel-body">
                                <table class="table table-print-list">
                                    <thead>
                                    <tr>
                                        <th>所屬分類</th>
                                        <th>產值事件</th>
                                        <th>產值型別</th>
                                        <th>產值最小值</th>
                                        <th>產值最大值</th>
                                        <th>經辦人</th>
                                        <th>稽核人</th>
                                        <th>管理</th>
                                    </tr>
                                    </thead>
                                    <tbody id="body_czevent">
                                    </tbody>
                                </table>
                                <nav class="text-right">
                                    <ul class="pagination" id="pagination_czevent">
                                    </ul>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
</body>
</html>

</span>
3、controller
<span style="font-size:12px;">package com.yiqi.controller.czmanager;

@Controller
@RequestMapping(value="/czevent")
public class CZEventController   extends Component<CzEvent>{
	private static String filename="";
	private Logger log = Logger.getLogger(CZEventController.class);
	 
		/**
		 * 上傳檔案到伺服器
		 * @param mvc
		 * @param request
		 * @param response
		 * @throws Exception 
		 */
		@RequestMapping(value="sendFile")
		public void sendFile (ModelAndView mvc,HttpServletRequest request,HttpServletResponse response) throws  Exception {
					request.setCharacterEncoding("utf-8"); // 設定編碼
					response.setCharacterEncoding("utf-8");
					response.setContentType("text/html;charset=UTF-8");
					//檔案儲存路徑
					String fileSavePath = request.getServletContext().getRealPath("/");//D:\apache-tomcat-7.0.57\webapps\yiqimanager-web
					fileSavePath = fileSavePath.substring(0,fileSavePath.indexOf("webapps")+7) + File.separator + "excel" + File.separator;
					ReturnJson json = new ReturnJson();
					UserInfo userInfo = this.getUser(request);
					String enterpriseid=userInfo.getEnterpriseid();
					// 獲得磁碟檔案條目工廠
					DiskFileItemFactory factory = new DiskFileItemFactory();
					File file = new File(fileSavePath);
					if(!file.exists()){
						file.mkdirs();
					}
					// 如果沒以下兩行設定的話,上傳大的 檔案 會佔用 很多記憶體,
					// 設定暫時存放的 儲存室 , 這個儲存室,可以和 最終儲存檔案 的目錄不同
					factory.setRepository(file);
					// 設定 快取的大小,當上傳檔案的容量超過該快取時,直接放到 暫時儲存室
					factory.setSizeThreshold(1024 * 1024);
					// 高水平的API檔案上傳處理
					ServletFileUpload upload = new ServletFileUpload(factory);
					try {
						// 請自行組織程式碼
						List<FileItem> list = upload.parseRequest(request);
						// 獲取上傳的檔案
						FileItem item = getUploadFileItem(list);
						// 獲取檔名
						filename = getUploadFileName(item);

						System.out.println("存放目錄:" + fileSavePath);
						System.out.println("檔名:" + filename);

						// 真正寫到磁碟上
						item.write(new File(fileSavePath, filename)); // 第三方提供的
						
					} catch (FileUploadException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}finally{
						String path=fileSavePath+filename;
						json.setError(Constants.JSON_SUCCESS);
						resolveExcel(path,enterpriseid,json);
						ResponseWriteUtils.returnAjax(response, json);
					}
		    }
		
		private FileItem getUploadFileItem(List<FileItem> list) {
			for (FileItem fileItem : list) {
				if(!fileItem.isFormField()) {
					return fileItem;
				}
			}
			return null;
		}
		private String getUploadFileName(FileItem item) {
			// 獲取路徑名
			String value = item.getName();
			// 索引到最後一個反斜槓
			int start = value.lastIndexOf("\\");
			// 擷取 上傳檔案的 字串名字,加1是 去掉反斜槓,
			String filename = value.substring(start + 1);
			
			return filename;
		}
		   /** 
	     * 解析excel檔案入庫
	     * @param args 
	     */  
	   private void resolveExcel(String filePath,String enterpriseid,ReturnJson json) throws Exception {  
	    	Excel excel =new Excel();
	    	Iterator<Row> it =excel.readExcel(filePath);
	    	//初始化批量新增/更新資料
	    	List<CzEvent> czEventList=new ArrayList<CzEvent>();
	    	String regex = ",|,|\\s+";
	        while (it.hasNext()) {
	        	CzEvent czEvent = new CzEvent();
	        	CzType czType = new CzType();
	        	czEvent.setCreatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
	            Row row = it.next();  
	            //如果第一列為空不讀
	            if(StringUtils.isBlank(excel.getCellFormatValue(row.getCell(0)))){
	            	continue;
	            }
	            int cellCount = row.getPhysicalNumberOfCells();  
	            for (int i = 0; i < cellCount; i++) {  
	                Cell cell = row.getCell(i);
	                //獲取每一行沒一列的值,從第二行開始就是我們需要的資料,需要在這裡set進對應的實體
	                String cellValue = excel.getCellFormatValue(cell); 
	                
	                if(row.getRowNum()>=2 && !StringUtils.isBlank(cellValue)){
	                	if (i==0) {//獲取第一列的資料
	                		//產值事件大類
	                		List<CzType> listType = czTypeService.queryCZnameList(cellValue,enterpriseid);
							
	                		if (listType.size()<1) {
								json.setError(Constants.JSON_ERROR);
								json.setMessage("【"+cellValue+"】"+"產值型別不存在");
								return;
							}else{
								String jktypeiddl = listType.get(0).getCztypeid().substring(0, 1);
								czEvent.setCzparentid(jktypeiddl);
								czType.setCztypeid(listType.get(0).getCztypeid());
							}
	                	} 
	                	if(i==1){//獲取第二列的資料
                			czEvent.setCzparentname(cellValue);
	                	}
	                	if(i==2){//獲取第三列的資料
	            			//事件名稱
							czEvent.setEventname(cellValue);
	                	}
	                	if(i==3){//獲取第四列的資料
	                		//產值型別
	                		if("實產值".equals(cellValue)){
	                			czEvent.setCztypeid("1");
	                		}else if("虛產值".equals(cellValue)){
	                			czEvent.setCztypeid("2");
	                		}else if ("創富產值".equals(cellValue)) {
	                			czEvent.setCztypeid("3");
							}else {
								json.setError(Constants.JSON_ERROR);
								json.setMessage("【"+cellValue+"】"+"產值型別不正確");
								return;
							}
	                	}
	                	if(i==4){//獲取第五列的資料
	                		//產值最小值
	                    	czEvent.setCzmin(cellValue);
	                	}
	                	if(i==5){//獲取第六列的資料
                			//產值最大值
	                		czEvent.setCzmax(cellValue);
	                	}
	                	if(i==6){//獲取第七列的資料
	                		//經辦人
	                	}
	                	if(i==7){//獲取第八列的資料
	                		//稽核人
	                	}
	                	if(i==8){ //獲取第九列的資料
	                		//備註
	                		czEvent.setRemark(cellValue);
	                	}
	                }
	            } 
	            if(row.getRowNum()>=2){
	            	if(!BeanUtils.isEmObject(czEvent)){
	            		String num = commonDao.getSeqNextvalByName("cz_czeventid");
	            		String czid = JournalSeq.getTableBusinessId("C", 7, num);
	            		czEvent.setCzid(czid);
	            		czEvent.setOrgid(enterpriseid);
	            		czEvent.setStatus('1');
	            		//自動填寫經辦人和稽核人
	            		czType = czTypeService.queryCZTypeById(czEvent.getTypeid());
                		czEvent.setOperatid(czType.getOperatid());
                		czEvent.setCheckedid(czType.getCheckedid());
                		czEvent.setInitEvent('0');
	            		czEventList.add(czEvent);
	            	}
	            }
	        } 
	        czEventService.insertBatchEvent(czEventList);//批量插入資料
	    }
}
</span>
4、Mapper.java
<span style="font-size:12px;">package czmanager;

@Repository
public interface CzEventMapper {
	//批量匯入事件 資訊
	public void insertBatchEvent(@Param("list")List<CzEvent> list);
	
}</span>

5、Mapper.xml
<span style="font-size:12px;"><insert id="insertBatchEvent" parameterType="com.yiqi.dao.entity.JkEvent" >
		insert into CZ_CZEVENT(czId, czParentId, czTypeId, eventName, 
		operatId, checkedId, remark,typeId,orgId,czmin,czmax,createTime,status,initEvent)
		values
		<foreach collection="list" item="item" index="index"
			separator=",">
			(#{item.czid},
			#{item.czparentid},
			#{item.cztypeid},
			#{item.eventname},
			#{item.operatid},
			#{item.checkedid},
			#{item.remark},
			#{item.typeid},
			#{item.Orgid},
			#{item.czmin},
			#{item.czmax},
			#{item.createtime},
			#{item.status},
			#{item.initEvent}
			)
		</foreach>
	</insert></span>

思路分析:

先下載上傳檔案模板→寫入資料→點選匯入→傳送請求到controller→讀取excel表格每一列的資料→呼叫service層→批量插入資料到資料庫