模板下载

需求:模板上传及下载

模板下载jsp代码如下:

<div id="select_condition">
			<div class="select_condition_row" name="form1" >
				  数据类型:
				<select style="width:110px;" id="select_con">
					<option value="1000" οnclick="selectBusinessHall()" >营业厅</option>
					<option value="1002" οnclick="selectVillageMessage()">4G参数</option>
					<option value="1003" οnclick="selectBasestationInforplan()">基站信息规划</option>
					<option value="1001" οnclick="showMr()">MR数据配置</option>
				</select>
				<span id="datePage" style="right:10px;position:absolute;"></span>
			</div>
			<div class="select_condition_row select_button" id="exim">
				<span><a οnclick="improtExample()">模板上传</a></span>
				<span><a οnclick="DownloadExample()">模板下载</a></span>
				<span><a οnclick="imports()">导入</a></span>
			</div>
			<input type="file" id="file" name=""   οnchange="fileChange(this)" style="FILTER: alpha(opacity=0); moz-opacity: 0; opacity: 0;" />
			<input type="file" id="uploadifys" name="myfiles"  multiple="multiple" οnchange="fileChanges(this)" style="FILTER: alpha(opacity=0); moz-opacity: 0; opacity: 0;" />
		</div>
<!-- 显示下载页面--》
<div id="showDiv" style='opacity:0.5; z-index: 100; position: fixed;width: 100%;height: 100%;background-color:#bebaba; display:none;'></div>
        <div id="checkDiv" style='z-index: 100; position: fixed; position: absolute;left: 32%;top: 10%;'>
            <div id="p" class="easyui-panel"
                style="width:525px; height: 452px; background: #fafafa;"
                title="模板下载" closable="true">
                <div class="select_condition_row1 select_button2">
                    <span ><a οnclick="downMessage()">模板下载</a></span>
                </div>
                <div class="checkContent">
                </div>
            </div>
        </div>

js代码如下:

/**
 * 模板上传,及下载
 */
function improtExample(){
	var ie = !-[1,];   
	if(ie){  
		$("#uploadifys").trigger('click').trigger('change');  
	}else{  
		$("#uploadifys").trigger('click');  
	}  
}

/**
 * 模板下载
 */
function DownloadExample(){

	$("#showDiv").show(); 
	$("#checkDiv >.panel").show();
	$.ajax({        
		type:'post',        
		url:path+'/SystemSiteController/listFile.do',    
		dataType:'json',  
		async: true,
		success:function(result){
			var jso = result.fileNameMap
			var htmls = "<table class='reason' style='width: 100%;'>";
			$.each(jso, function(i,val){
				htmls = htmls + "<tr><td ><label style='padding-left: 9px;'><input name='Fruit' type='checkbox' value='"+val+"' />"+val+" </label</td></tr>"
			});
			htmls = htmls + "</table>"
			$(".checkContent").html(htmls);
		}
	});

}

/**
 *  模板下载上传下载目录
 */
function downMessage(){
	text = $("input:checkbox[name='Fruit']:checked").map(function(index,elem) {
		return $(elem).val();
	}).get().join(',');
	window.location.href = path+'/SystemSiteController/downListFile.do?fileName='+text;
}

/**
 * 模板下载显示下载目录
 * @param cellName
 */
function checkOrder(objectid, cellName){
	$.ajax({        
		type:'post',        
		url:path+'/SystemSetting/listFile.do',    
		dataType:'json',  
		async: true,
		success:function(result){
		}
	});
}

controller的代码如下:

/**
	 * 列出模板下载需要下载的文件
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("listFile")
	public ModelAndView listFile(HttpServletRequest request,HttpServletResponse response){
		
		//获取上传文件的目录
//		String uploadFilePath = (request.getSession().getServletContext().getRealPath("")).replace("\\", "/") +"systemPage";
		String uploadFilePath = request.getSession().getServletContext().getRealPath("/systemPage");
		//存储要下载的文件名
		Map<String,String> fileNameMap = new HashMap<String,String>();
		//递归遍历filepath目录下的所有文件和目录,将文件的文件名存储到map集合中
		(new DownLoadFile()).listfile(new File(uploadFilePath),fileNameMap);//File既可以代表一个文件也可以代表一个目录
		Map<String,Object> attributes = new HashMap<String,Object>();
		attributes.put("fileNameMap", fileNameMap);
		MappingJackson2JsonView view = new MappingJackson2JsonView();
		view.setAttributesMap(attributes);
		ModelAndView model = new ModelAndView();
		model.setView(view);
		return model;
	}
	
	/**
	 * 模板下载
	 * @param request
	 * @param response
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("downListFile")
	public static void downListFile(HttpServletRequest request, HttpServletResponse response)throws Exception {
		
		String fileName  = request.getParameter("fileName");
		String[] fileNames = fileName.split(",");
		//文件的目录
		String uploadFilePath = request.getSession().getServletContext().getRealPath("/systemPage");
		//这个集合就是你想要打包的所有文件
		List<File> files = new ArrayList<File>();
		for (int i = 0; i < fileNames.length; i++) {
			String path = uploadFilePath +"/"+fileNames[i];
			File ff = new File(path);
			files.add(ff);
		}
		
		try {
			//创建一个临时压缩文件, 我们会把文件流全部注入到这个文件中 ,这里的文件你可以自定义是.rar还是.zip
			File file = new File("c:/DataTemplate.rar");
			if (!file.exists()){   
			    file.createNewFile();   
			}
			response.reset();
			//response.getWriter()
			//创建文件输出流
			FileOutputStream fous = new FileOutputStream(file); 
			
			//打包的方法我们会用到ZipOutputStream这样一个输出流,所以这里我们把输出流转换一下
			ZipOutputStream zipOut = new ZipOutputStream(fous,StandardCharsets.UTF_8);
			
			//这个方法接受的就是一个所要打包文件的集合,还有一个ZipOutputStream
			(new DownLoadFile()).zipFile(files, zipOut);
			zipOut.close();
			fous.close();
			(new DownLoadFile()).downloadZip(file,response);
		}catch (Exception e) {
		    e.printStackTrace();
		}
	}
	

package com.sls.framework.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;


/** 
* @version 创建时间:2016年4月27日 下午4:45:23 
*  文件下载帮助类
*/
public class DownLoadFile {

	/**
	 * 遍历文件夹里的所有文件夹名
	 * @param file
	 * @param map
	 */
	public void listfile(File file,Map<String,String> map){
		//如果file代表的不是一个文件,而是一个目录
		if(!file.isFile()){
			//列出该目录下的所有文件和目录
			File files[] = file.listFiles();
			//遍历files[]数组
			for(File f : files){
				//递归
				listfile(f,map);
			}
		}else{
			/**
			* 处理文件名,上传后的文件是以uuid_文件名的形式去重新命名的,去除文件名的uuid_部分
			file.getName().indexOf("_")检索字符串中第一次出现"_"字符的位置,如果文件名类似于:9349249849-88343-8344_阿_凡_达.avi
			那么file.getName().substring(file.getName().indexOf("_")+1)处理之后就可以得到阿_凡_达.avi部分
			*/
			String realName = file.getName().substring(file.getName().indexOf("_")+1);
			//file.getName()得到的是文件的原始名称,这个名称是唯一的,因此可以作为key,realName是处理过后的名称,有可能会重复
			map.put(file.getName(), realName);
		 }
	}

	/**
	 * 把接受的全部文件打成压缩包 
	 * @param List<File>;  
	 * @param org.apache.tools.zip.ZipOutputStream  
	 */
	public static void zipFile(List files,ZipOutputStream outputStream) {
		
	    int size = files.size();
	    for(int i = 0; i < size; i++) {
	        File file = (File) files.get(i);
	        zipFile(file, outputStream);
	    }
	}
	
	/**  
	 * 根据输入的文件与输出流对文件进行打包
	 * @param File
	 * @param org.apache.tools.zip.ZipOutputStream
	 */
	public static void zipFile(File inputFile,ZipOutputStream ouputStream) {
	    try {
	        if(inputFile.exists()) {
		        //如果是目录的话这里是不采取操作的,至于目录的打包正在研究中
		        if (inputFile.isFile()) {
		            FileInputStream IN = new FileInputStream(inputFile);
		            BufferedInputStream bins = new BufferedInputStream(IN, 512);
		            //org.apache.tools.zip.ZipEntry
		            ZipEntry entry = new ZipEntry(inputFile.getName());
		            ouputStream.putNextEntry(entry);
		            // 向压缩文件中输出数据   
		            int nNumber;
		            
		            byte[] buffer = new byte[512];
		            while ((nNumber = bins.read(buffer)) != -1) {
		                ouputStream.write(buffer, 0, nNumber);
		            }
		            // 关闭创建的流对象   
		                bins.close();
		                IN.close();
		            } else {
		                try {
		                    File[] files = inputFile.listFiles();
		                    for (int i = 0; i < files.length; i++) {
		                        zipFile(files[i], ouputStream);
		                    }
		                } catch (Exception e) {
		                    e.printStackTrace();
		                }
		            }
	        }
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	}
	
	/**
	 * 已流的=下载
	 * @param file
	 * @param response
	 */
    public static void downloadZip(File file,HttpServletResponse response) {
        try {
	        // 以流的形式下载文件。
	        InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
	        byte[] buffer = new byte[fis.available()];
	        fis.read(buffer);
	        fis.close();
	        // 清空response
	        response.reset();
	
	        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
	        response.setContentType("application/octet-stream");
	
	        //如果输出的是中文名的文件,在此处就要用URLEncoder.encode方法进行处理
	        response.setHeader("Content-Disposition", "attachment;filename=" +URLEncoder.encode(file.getName(), "UTF-8"));
	        toClient.write(buffer);
	        toClient.flush();
	        toClient.close();
        } catch (IOException ex) {
        	ex.printStackTrace();
        }finally{
			try {
//			       File f = new File(file.getPath());
//			       f.delete();
			   } catch (Exception e) {
			        e.printStackTrace();
			   }
        }
    }


}



  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值