文件上传及解压

前段时间遇到需求,.gz压缩文件上传及解压:

其中ajaxFileUplad文件上传需要ajaxfileupload.js文件

ajaxfileupload.js如下:

// JavaScript Document
jQuery.extend({

    createUploadIframe: function(id, uri)
 {
   //create frame
            var frameId = 'jUploadFrame' + id;
            
            if(window.ActiveXObject) {
            	if(jQuery.browser.version=="9.0") {
            		io = document.createElement('iframe');
            		io.id = frameId;
            		io.name = frameId;
            	} else if(jQuery.browser.version=="6.0"||jQuery.browser.version=="7.0"||jQuery.browser.version=="8.0") {
            		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;
    }
});

前台html需要引入ajaxfileupload.js文件,代码如下:

<script src="<%=request.getContextPath()%>/common/resource/js/ajaxfileupload.js" type="text/javascript"></script>
<script type="text/javascript">
	var path = "<%=request.getContextPath()%>";
	var role = "<%=request.getSession().getAttribute("role")%>";
</script>

前台html代码如下:

<div id="mainDiv_4G" style="height: 342px; ">
	    	<div  style="height: 40px;border: 1px solid #4C9ED9;"><center><span id="loggingLabel">MR数据配置</span></center></div>
	    	<div id="mrdiv"><label id="mrlableId">MR数据配置:</label>
	    	    <input type="file"  name="myfiles" id="uploadify"   multiple="multiple" />  
                <input id="fileButton" type="button" value="上传" onclick="improtMessage()" /> 
                <input id="fileButton" type="button" value="入库" onclick="pressMREGZIP()" /> 
                <label id="warning" style="font-size: 118%;color: #F00;margin-left: 8px;position: absolute;margin-top: 11px;"></label>  
	    	</div>
	    </div>

前台js代码如下:

  /**
 * 导入mr配置
 */
function improtMessage() {
	$("#warning").html("");
	 var ss = document.getElementById("uploadify").files;//js中取到其中对象
//	 var fileName=$("#uploadify")[0].files[0].name;
	if((ss.length)!=0){
		$("#warning").html("文件正在上传中,请耐心等待!!");
		$.messager.confirm('提示','确定您要导入配置?',function(r){
			if (r){
			//	$('#uploadify').attr("name",$('#uploadify').val());
				$.ajaxFileUpload({
					url: path+'/systemConfigureController/importMRData.do',
					secureuri: false,//异步
					fileElementId: 'uploadify',//上传控件ID
					dataType: 'text',//返回的数据信息格式
					success: function(data){
						if(data == "<pre>true</pre>"){
							$("#warning").html("文件上传成功!");
						}
					}
				})
			}
		});
	}else{
		$.messager.alert('提示',"请先选择文件!!");
	}
}

后台controller代码如下:

/**
 * 导入MD数据配置
 * @param request
 * @param response
 * @throws IOException
 */
@RequestMapping("importMRData")
public void importMRData(HttpServletRequest request, HttpServletResponse response, @RequestParam MultipartFile[] myfiles) throws IOException {
	logger.info("**********into method importData*************");
	boolean isTrue = false;
	// 设置上下文
//	MultipartFile myfile = myfiles[1];
//	System.out.println("name="+myfile.getName()+",size="+ myfile.getSize()+ ",OriginalFilename="+ myfile.getOriginalFilename() );
	InputStream is = null;
	FileOutputStream output = null;
	String savePath = null;
		for(int i=0;i<myfiles.length;i++){
			MultipartFile myfile = myfiles[i];
			String myfileName = myfile.getOriginalFilename();
			try {
				is = myfile.getInputStream();//MultipartFile转成输入流FileOutputStream
				if(myfileName.contains("MRE")){
//					savePath = "E:\\MRE\\"+ myfile.getOriginalFilename();
					savePath = "/sdb/mre/"+ myfile.getOriginalFilename();
				}
				if(myfileName.contains("MRS")){
//					savePath = "E:\\MRS\\"+ myfile.getOriginalFilename();	
					savePath = "/sdb/mrs/"+ myfile.getOriginalFilename();	
				}
				if(myfileName.contains("MRO")){
//					savePath = "E:\\MRO\\"+ myfile.getOriginalFilename();	
					savePath = "/sdb/mro/"+ myfile.getOriginalFilename();	
				}
				output = new FileOutputStream(savePath);
	            byte[] b = new byte[1024];
	            while (is.read(b) != -1) {
	                output.write(b);
	                b = new byte[1024];
	            }
			} catch (IOException e) {
				response.getWriter().print(isTrue);
			}
		}
	 try {
		isTrue = true;
		response.getWriter().print(isTrue);
	} catch (IOException e1) {
		e1.printStackTrace();
	}
    try {
			output.close();
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
    //解压文件
   
//    String 	mreFileName = "E:\\MRE";
//    String mroFileName = "E:\\MRO";
//    String mrsFileName = "E:\\MRS";	
    String 	mreFileName = "/sdb/mre";
    String mrsFileName = "/sdb/mrs";
    String mroFileName = "/sdb/mro";
    File mrefile = new File(mreFileName);   
	File[] mrearray = mrefile.listFiles();
	File mrofile = new File(mroFileName);   
	File[] mroarray = mrofile.listFiles();
	File mrsfile = new File(mrsFileName);   
	File[] mrsarray = mrsfile.listFiles();
	if(mrearray.length!=0){//解压Mre
		boolean isPass = UncompressFileGZIP.doUncompressFile(mrearray); 
		UncompressFileGZIP.delectFile(mrearray);
	}
	if(mroarray.length!=0){//解压MRO
		boolean isPass = UncompressFileGZIP.doUncompressFile(mroarray); 
		UncompressFileGZIP.delectFile(mroarray);
	}
	if(mrsarray.length!=0){//解压MRS
		boolean isPass = UncompressFileGZIP.doUncompressFile(mrsarray); 
		UncompressFileGZIP.delectFile(mrsarray);
	}
  }

文件解压代码如下:

package com.hrtel.framework.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
/**
 * 文件解压帮助类
 * @author hr
 *
 */
public class UncompressFileGZIP { 

	public static boolean doUncompressFile( File[] array) { 
    	boolean isTrue = true;
//    	   File file = new File(path);   
//    	   File[] array = file.listFiles();   //列出指定文件夹下的文件
    	   for(int i=0;i<array.length;i++){   
               if(array[i].isFile()){  
                String inFileName = array[i].getPath();
                if(inFileName.endsWith(".gz")){
                	   try { 
          	            System.out.println("Opening the compressed file."); 
          	            GZIPInputStream in = null; 
          	            try { 
          	                in = new GZIPInputStream(new FileInputStream(inFileName)); 
          	            } catch(FileNotFoundException e) { 
          	                System.err.println("File not found. " + inFileName); 
          	                isTrue = false;
          	            } 

          	            System.out.println("Open the output file."); 
          	            String outFileName = getFileName(inFileName); 
          	            FileOutputStream out = null; 
          	           try { 
          	                out = new FileOutputStream(outFileName); 
          	            } catch (FileNotFoundException e) { 
          	                System.err.println("Could not write to file. " + outFileName); 
          	                isTrue = false;
          	            } 

          	            System.out.println("Transfering bytes from compressed file to the output file."); 
          	            byte[] buf = new byte[1024]; 
          	            int len; 
          	            while((len = in.read(buf)) > 0) { 
          	                out.write(buf, 0, len); 
          	            } 
          	            System.out.println("Closing the file and stream"); 
          	            in.close(); 
          	            out.close(); 
         	           } 
                	   catch (IOException e) { 
          	            e.printStackTrace(); 
                	   } 
                
                }else{//其他压缩格式文件
                	isTrue = false;
                }
             } 
    	  }
		return isTrue;
    } 

    public static String getExtension(String f) { 
        String ext = ""; 
        int i = f.lastIndexOf('.'); 

        if (i > 0 &&  i < f.length() - 1) { 
            ext = f.substring(i+1); 
        } 
        System.out.println(ext);
        return ext; 
    } 

    public static String getFileName(String f) { 
        String fname = ""; 
        int i = f.lastIndexOf('.'); 

        if (i > 0 &&  i < f.length() - 1) { 
            fname = f.substring(0,i); 
        }      
        return fname; 
    } 
    
    //删除解压后的文件
    public static void delectFile(File[] array){
//    	 File file = new File(path);   
//  	   File[] array = file.listFiles();   //列出指定文件夹下的文件
  	   for(int i=0;i<array.length;i++){   
  		  System.gc();
             if(array[i].isFile()){  
             String inFileName = array[i].getPath();
             File f = new File(inFileName); // 输入要删除的文件位置
             System.out.println(inFileName);
             if(inFileName.endsWith(".gz")){
	           	if(f.exists()){
          		   boolean d = f.delete();
          		    if(d){
          		     System.out.println("删除成功!");
          		    }else{
          		     System.out.println("删除失败!");
          		    }
	          	}
             }
          }
  	   }
    }
}





你可能感兴趣的:(文件上传及解压)