欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

文件下载

程序员文章站 2022-03-04 16:19:15
...

单个文件下载:

openCl: function(e){
    	var khcl = $(e.target).attr("data-x-khcl");
    	var wid = $(e.target).attr("data-x-wid");
    	var px = $(e.target).attr("data-x-px");
		 if( khcl!=undefined && khcl!='null' && khcl!=''){
	    	 var fileName =  px + "_" + $(e.target).attr("data-x-wjm");
//	    	 fileName = fileName.split(".")[0];
	    	 fileName = fileName.substring(0, fileName.lastIndexOf('.'));
	    	 bs.save({WID:wid,XZZT:'2'});//2:已下载
	    	 window.open("../XX/downloadOne.do?fileUrl="+khcl+"&fileName="+encodeURI(fileName));
		 }else{
			 alert('没有上传材料!');
			   		
		 }
    },
 //单个文件下载
    @RequestMapping({"downloadOne"})
    @ResponseBody
    public void downloadOne(HttpServletRequest request,HttpServletResponse res)throws ServletException, IOException {
    	 res.setContentType("text/html; charset=UTF-8"); //设置编码字符  
         res.setContentType("application/octet-stream;charset=UTF-8"); //设置内容类型为下载类型  
         String fileUrl = request.getParameter("fileUrl");
         String fileName = request.getParameter("fileName");
       
         //处理文件名有中文问题    
         fileName= java.net.URLDecoder.decode(fileName,"UTF-8");
         //处理文件名有中文问题    
         if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {//谷歌浏览器
        	 fileName= URLEncoder.encode(fileName,"UTF-8");
         } else {
        	 fileName= new String(fileName.getBytes(),"ISO-8859-1");
         }
         
         String suffix = fileUrl.substring(fileUrl.lastIndexOf(".")+1);
         String fileNameOne = fileName + "." + suffix;
         String filePath = "http://" + fileUrl;
         if (null == filePath || filePath.length() == 0) {
             throw new RuntimeException("remoteFileUrl is invalid!");
         }

         URL url = new URL(filePath);
         BufferedInputStream in = null;
         // URLConnection conn = url.openConnection();
         // in = new BufferedInputStream(conn.getInputStream());
         // 这和上面两句一样的效果
         in = new BufferedInputStream(url.openStream());
         res.reset();
         res.setHeader("Content-Disposition","attachment;filename=\""+fileNameOne+"\"");
         // 将网络输入流转换为输出流
         int i;
         while ((i = in.read()) != -1) {
        	 res.getOutputStream().write(i);
         }
         in.close();
         res.getOutputStream().close();
    }

 

多个文件下载:

 downLoadAll: function(){
    	var arrayObj = new Array();
    	var fileNameObj = new Array();
    	var arr;
    	var fileNameArr;
    	var row = $("#emapdatatable").emapdatatable("checkedRecords");
        if(row.length > 0){
        	var jsonArr = [];
            var params = row.map(function(el){
            	jsonArr.push({WID:el.WID,XZZT:'2'});
            	return {WID:el.WID, FILEURL:el.FILEURL, WJM:el.WJM, PX:el.PX};  //模型主键
           });
            var i = 0;
            $.each(params,function(key,val){
          	  var fj = params[key].FILEURL;
			  if( fj!=undefined && fj!='null' && fj!=''){
				  arrayObj[i] = fj;
				  fileNameObj[i] = params[key].PX==null? params[key].WJM : params[key].PX + "_" + params[key].WJM;
				  console.info(fileNameObj[i]);
				  i++;
			  }
              arr = arrayObj.join();
              fileNameArr = fileNameObj.join();
            });
            
            //批量修改下载状态
            var p = {T_RS_NKD_RSKH_KHCL_SAVE : JSON.stringify(jsonArr)};
            bs.save(p);
            
            var winHeight = window.document.documentElement.clientHeight-10;
//请求地址
//            var url = WIS_CONFIG.ROOT_PATH + '/score-generator/downloads.do';
            var url = WIS_CONFIG.ROOT_PATH + '/score-generator/batchExportPic2.do';

            var formStr = '<form style="visibility:hidden;" method="POST" action="' + url + '">' +
            						'<input type="hidden" name="arr" value="' + arr + '" />'+
                                    '<input type="hidden" name="fileNameArr" value="' + fileNameArr + '" />' +
                                    '</form>';

            var win = window.open("");
            win.document.body.innerHTML = formStr;
            win.document.forms[0].submit();
            
        }
    },
 /**
	 * 批量导出文件
	 * 1.先获取批量的文件地址, 
	 * 1.循环 将每个文件复制到
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException 
	 * @throws SQLException 
	 */
	@RequestMapping({ "/batchExportPic2" })
	public void buildZipFile2(HttpServletRequest request,HttpServletResponse response) throws Exception{
		long startTime=System.currentTimeMillis();
		String fileName = "述职文件.zip";
		response.setContentType("APPLICATION/OCTET-STREAM");
		response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(fileName,"UTF-8"));
		String[] fileUrls = request.getParameter("arr").split(",");
		String[] xhs   = request.getParameter("fileNameArr").split(",");
		DxRestTemplate rest =   DxRestTemplate.getInstance();
		ZipOutputStream zipos = null;
		DataOutputStream os = null;
		try {
			zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
			zipos.setMethod(ZipOutputStream.DEFLATED);// 设置压缩方法DEFLATED
			zipos.setEncoding("GBK");
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 线程池改造,
		// 1.将数据分片
		// 2.集合运算
		System.err.println("几核"+Runtime.getRuntime().availableProcessors());
		ExecutorService service = new ThreadPoolExecutor(3,8,1,TimeUnit.MINUTES,
				new ArrayBlockingQueue<Runnable>(3));
		int size = fileUrls.length > 12 ? fileUrls.length/10 : 5 ;
		int round = fileUrls.length % size == 0 ? fileUrls.length/size : fileUrls.length/size + 1;
		System.out.println("共有几轮线程:"+round);
		CountDownLatch latch = new CountDownLatch(round);
		Lock lock = new ReentrantLock();
		for (int i = 1; i <= round; i++) {
			service.submit(new MultiBuildZipFiles(i, size, fileUrls, xhs, zipos, latch, lock));
		}
		latch.await();
		try {
			System.out.println("-----------线程池已执行完毕------------------");
			long endTime=System.currentTimeMillis();
			float excTime=(float)(endTime-startTime)/1000;
			System.out.println("执行时间:"+excTime+"s");
			zipos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			service.shutdown();
		}
		
	}

MultiBuildZipFiles.java


import java.io.DataOutputStream;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

/**
 * 文件下载
 * @author weifuchow
 *
 */
public class MultiBuildZipFiles implements Runnable {

	private int pageIndex;
	
	private int pageSize;
	
	private int index;
	
	private int end;
	
	private String[] fileUrls;
	private String[] xhs;
	
	private Lock lock;
	private ZipOutputStream zipos = null;
	
	private CountDownLatch latch ; 

	public MultiBuildZipFiles(int index, int size, String[] fileUrls,String [] xhs,ZipOutputStream zipos,
			CountDownLatch latch,Lock lock) {
		super();
		this.pageIndex = index;
		this.pageSize = size;
		this.fileUrls = fileUrls;
		this.xhs = xhs;
		int total = fileUrls.length;
		this.lock = lock;
		// 1   0 5
		// 2   5 10
		// 3   10 14
		this.index = (pageIndex - 1) * pageSize;
		this.end   =  Math.min(pageIndex * pageSize,total) ;
		this.zipos = zipos;
		this.latch = latch;
	}

	
	
	public void run() {
		// TODO 自动生成的方法存根
		// 计算开始节点 结束节点
		try {
			for (int i = index; i < end; i++) {
				String url = fileUrls[i];
				DxRestTemplate rest =   DxRestTemplate.getInstance();
				byte[] data = rest.doGetForStream("http://" + url);
				try{
					lock.lock();
					System.out.println(Thread.currentThread().getName()+"-->正在执行合并"+i+"照片");
					zipos.putNextEntry(new ZipEntry(xhs[i]));
					DataOutputStream os = new DataOutputStream(zipos);
					os.write(data);
					zipos.closeEntry();
					data = null;// 回收
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					lock.unlock();
					System.out.println(Thread.currentThread().getName()+"操作资源:"+i+" 释放锁--》");
				}
			}
		} 
		catch(Exception e){
			e.printStackTrace();
		}
		finally {
			// TODO: handle finally clause
			System.out.println(Thread.currentThread().getName()+"执行完毕");
			latch.countDown();
		}
		
	}
	
}

下面这种方式作废:有bug,批量下载的第一个文件会乱码,文件10个以上就会太长时间然后卡死,不是异步请求下载,浏览器太长时间没有接收到返回信息导致。

 //批量打包下载
    @RequestMapping({"downloads"})
    @ResponseBody
    public void downloads(HttpServletRequest request,HttpServletResponse res)throws ServletException, IOException {
    	//方法1:IO流实现下载的功能  
        res.setContentType("text/html; charset=UTF-8"); //设置编码字符  
        res.setContentType("application/octet-stream;charset=UTF-8"); //设置内容类型为下载类型  
        System.out.println(request.getRealPath("/"));
    	String arr = request.getParameter("arr");
    	String[] filepath = arr.split(",");
    	String fileNameArr = request.getParameter("fileNameArr");
    	//处理文件名有中文问题    
    //	fileNameArr = java.net.URLDecoder.decode(fileNameArr,"UTF-8");
    	String[] fileNames = fileNameArr.split(",");
        //创建压缩文件需要的空的zip包  
        String zipBasePath = request.getRealPath("/rskhsfDownLoad");
        FileUtil.delFolder(zipBasePath);  
        File fileTemp=new File(zipBasePath);
        if(!fileTemp.exists()){//如果文件夹不存在
        	fileTemp.mkdir();//创建文件夹
		}
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        	String date = df.format(new Date());
            String zipName = date+".zip";
            //在本地创建文件
            String zipFilePath = zipBasePath+File.separator+zipName;
            //压缩文件
            File zip = new File(zipFilePath);  
            if (!zip.exists()){     
                zip.createNewFile();     
            }
            //创建需要下载的文件路径的集合
            List<String> filePaths = new ArrayList<String>();  
            for(int i=0; i<filepath.length; i++){
            	String targetPath = "http://"+filepath[i];
            	filePaths.add(targetPath);  
            }
            //创建zip文件输出流  
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip));
            this.zipFile(zipName,filePaths,zos,fileNames, request);
            zos.close();
            res.setHeader("Content-disposition", "attachment;filename="+zipName);//设置下载的压缩文件名称
            OutputStream out = res.getOutputStream();   //创建页面返回方式为输出流,会自动弹出下载框   
            //将打包后的文件写到客户端,输出的方法同上,使用缓冲流输出  
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipFilePath));  
            byte[] buff = new byte[bis.available()];  
            bis.read(buff);
            bis.close();
            out.write(buff);//输出数据文件
            out.flush();//释放缓存
            out.close();//关闭输出流
		} catch (Exception e) {
			e.printStackTrace();
		}
        
        
    }
    /**
     * 压缩文件
     * @param zipBasePath 临时压缩文件基础路径
     * @param zipName 临时压缩文件名称
     * @param zipFilePath 临时压缩文件完整路径
     * @param filePaths 需要压缩的文件路径集合
     * @throws IOException
     */
    //String zipBasePath,
    private String zipFile( String zipName, List<String> filePaths,ZipOutputStream zos,String[] fileNames, HttpServletRequest request) throws IOException {
    	//循环读取文件路径集合,获取每一个文件的路径  
        //for(String filePath : filePaths){  
        for(int k =0; k<filePaths.size();k++){
            URL urlfile = null;
            HttpURLConnection httpUrl = null;
            BufferedInputStream bis = null;
            //创建输入流读取文件  
            System.out.println(filePaths.get(k));
            urlfile = new URL(filePaths.get(k));
            httpUrl = (HttpURLConnection) urlfile.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            String suffix= filePaths.get(k).substring(filePaths.get(k).lastIndexOf(".")+1);
            String fileName = fileNames[k];
            //处理文件名有中文问题    
            fileName= java.net.URLDecoder.decode(fileName,"UTF-8");
            //处理文件名有中文问题    
            if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
           	 fileName= URLEncoder.encode(fileName,"UTF-8");
            } else {
           	 fileName= new String(fileName.getBytes(),"UTF-8");
            }
            //将文件写入zip内,即将文件进行打包  
            zos.putNextEntry(new ZipEntry(fileName));  
            zos.setEncoding("GBK");//重要,GBK线上压缩文件夹里面的文件名称不会乱码
            //写入文件的方法,同上                  
            int size = 0;  
            byte[] buffer = new byte[1024];  //设置读取数据缓存大小
            while ((size = bis.read(buffer)) > 0) {  
                zos.write(buffer, 0, size);  
            }  
            //关闭输入输出流  
            zos.closeEntry();  
            bis.close(); 
            httpUrl.disconnect();
        }  
        return null;
    } 

 

相关标签: 常用工具