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

文件下载

程序员文章站 2022-06-20 09:03:32
...

图片下载

一、单个文件下载

     前端
     <a class="btn btn-primary btn-download"             
     style="width:30px;height:30px;position:absolute;top:50px;left:50px;" 
     href="${pageContext.request.contextPath}/downloadOneFile.do?
     fileUrl=http://xxx.net/assess/11141.jpg&fileName=${status.index+1}">下载
     </a>


     后端
     /** 
     * TODO 下载单个文件到本地
     * @param fileUrl 远程地址
     * @param fileLocal 本地路径
     * @throws Exception 
     */
    @RequestMapping(value = "downloadOneFile.do")
    public void downloadFile(
    		String fileUrl,
    		String fileName,
    		HttpServletRequest request,
    		HttpServletResponse response) throws Exception {        
		String pString=fileUrl.substring(fileUrl.lastIndexOf("."));
		System.out.println(pString);
        response.setContentType("text/html;charset=UTF-8");  
        BufferedInputStream in = null;    
        BufferedOutputStream out = null;   
        URL url = new URL(fileUrl);
        HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
        urlCon.setConnectTimeout(6000);
        urlCon.setReadTimeout(6000);
        int code = urlCon.getResponseCode();
        if (code != HttpURLConnection.HTTP_OK) {
            throw new Exception("文件读取失败");
        }
        try { 
	        response.setContentType("multipart/form-data");    
	        response.setCharacterEncoding("UTF-8");    
	        response.setHeader("Content-Disposition", "attachment;         
            filename="+java.net.URLEncoder.encode(fileName,"UTF-8")+pString);    
	        response.setHeader("Content-Length",String.valueOf(urlCon.getContentLength()));    
	        in = new BufferedInputStream(urlCon.getInputStream());    
	        out = new BufferedOutputStream(response.getOutputStream());    
	        byte[] data = new byte[1024];    
	        int len = 0;    
	        while (-1 != (len=in.read(data, 0, data.length))) {    
	            out.write(data, 0, len);    
	        }  
	        System.out.println("下载成功");
	    }catch (Exception e) {    
		        e.printStackTrace();    
		}finally {    
	        if (in != null) {    
	            in.close();    
	        }    
	        if (out != null) { 
	        	out.flush();
	            out.close();    
	        }    
		}    
	}

二、多个文件打包下载
 

前端
<a href="${pageContext.request.contextPath}/downloadFile_all.do?type=zdr&id=${pd.id}&base_name=主贷人材料" class="myself">批量下载</a>

后端
/**
     * what 打包下载多个文件到本地并压缩 
     * when 2018-8-25
     * who  hzj
     * @param type 文件保存的数组
     * EG::type=[upload/2018/06/30/5d8d81f9a88d64e6e803bb499b870419.jpg, upload/2018/06/30/e495e0311096d997e8c54fd3fce2cf7a.jpg, upload/2018/06/30/183ae07a0d0ff07df8bcc798ea3e2700.jpg, upload/2018/06/30/f14add7bca1db43f1abb1e337672c22b.jpg, upload/2018/06/30/a42bc885f06b67aafd3fbad7351b2de6.jpg, upload/2018/06/30/1e71ca7c23cf5179ac921a17f0bfe174.jpg, upload/2018/06/30/68c9d4257399ac293c1644a9f514d224.jpg, , ]
     *
     */
	@RequestMapping(value = "erp/downloadFile_all.do")
	@ResponseBody
    public void downloadFile_all(
	    		String type,
	    		String id,
	    		String base_name,
	    		HttpServletRequest request,
	    		HttpServletResponse response)throws Exception {
	        response.setContentType("application/json;charset=utf-8");  
	        List<imgfile> FileNameList =new ArrayList<imgfile>(); // 用于存放即将下载的照片
	        //压缩文件名字
	        if(base_name.equals("") ||  base_name==null){
	        	base_name =UUID.randomUUID().toString().replaceAll("-","");	
	        }
	        base_name = new String(base_name.getBytes("ISO-8859-1"),"UTF-8");
	        base_name = new String(base_name.getBytes("GB2312"),"ISO-8859-1");
	        //方法查到五张表全部的信息
	        PageData pData = new PageData();
			pData.put("dn","icbc_erp_kj_icbc");
			pData.put("icbc_id",id);		
			System.out.println("主订单id:"+id);
			if (id != null && !id.equals("")) {
				//得到五张表全部的信息
				PageData pageData = erp_wdrwService.icbc_form(pData);
				String khName= new String(pageData.getString("c_name").getBytes("GB2312"),"ISO-8859-1");
				System.out.println("客户姓名:"+pageData.get("c_name"));
				base_name =khName+"_"+base_name;
				int imgCounts = 1;
				if (pageData != null && !pageData.equals("")){
					//XX材料
					if(type.equals("xx")){
						List<Object> zxImgsList = new ArrayList<>();
						Object imgss1 = (String) pageData.get("imgstep2_1ss") + pageData.get("imgstep2_2ss")+ pageData.get("imgstep2_3ss") + pageData.get("imgstep2_4ss");
						String[] zx_imgs = null;
						imgss1 = imgss1.toString().replace("null","");
						if (imgss1 != null && !imgss1.equals("")){
							zx_imgs = ((String) imgss1).split("");
							if (zx_imgs.length > 0){
								for(int i=0;i<zx_imgs.length;i++){
						        	if(zx_imgs[i]!=null&&!zx_imgs[i].equals("")){
					        			imgfile imgfile=new imgfile();
										imgfile.setImgurl("http://a.kcway.net/assess/"+zx_imgs[i]);
										imgfile.setName(i+1+"");
										imgfile.setFilelast(((String)zx_imgs[i]).substring(((String)zx_imgs[i]).lastIndexOf(".")+1,((String)zx_imgs[i]).length()));
										FileNameList.add(imgfile);	
										imgCounts++;
					        		}
								}
							}
						}
					}
					if(type.equals("sq")){
						List<Object> sqList = new ArrayList<>();
						sqList.add(pageData.get("imgstep8_1v"));
						sqList.add(pageData.get("imgstep8_2v"));
						sqList.add(pageData.get("imgstep8_3v"));
						sqList.add(pageData.get("imgstep8_4v"));
						//给每张图片设置url,name,后缀名
						if(sqList.size()>0){
					        for(int i=0;i<sqList.size();i++){
					        	if(sqList.get(i)!=null&&!sqList.get(i).equals("")){
				        			imgfile imgfile=new imgfile();
									imgfile.setImgurl("http://a.kcway.net/assess/"+sqList.get(i));
									imgfile.setName(i+1+"");
									imgfile.setFilelast(((String)sqList.get(i)).substring(((String)sqList.get(i)).lastIndexOf(".")+1,((String)sqList.get(i)).length()));
									FileNameList.add(imgfile);	
									imgCounts++;
				        		}
							}
				        }
					}
					if(type.equals("qy")){
						List<Object> qyImgsList = new ArrayList<>();
						Object imgss1 = (String) pageData.get("imgstep4_1ss") + pageData.get("imgstep4_2ss")+ pageData.get("imgstep4_3ss") + pageData.get("imgstep4_4ss") + pageData.get("imgstep4_5ss");
						String[] qy_imgs = null;
						imgss1 = imgss1.toString().replace("null","");
						// 签约材料
						if(imgss1 != null && !imgss1.equals("")){
							qy_imgs = ((String) imgss1).split("");
							if (qy_imgs.length > 0){
								for(int i=0;i<qy_imgs.length;i++){
						        	if(qy_imgs[i]!=null&&!qy_imgs[i].equals("")){
					        			imgfile imgfile=new imgfile();
										imgfile.setImgurl("http://a.kcway.net/assess/"+qy_imgs[i]);
										imgfile.setName(i+1+"");
										imgfile.setFilelast(((String)qy_imgs[i]).substring(((String)qy_imgs[i]).lastIndexOf(".")+1,((String)qy_imgs[i]).length()));
										FileNameList.add(imgfile);	
										imgCounts++;
					        		}
								}
							}
						}
					}
				}
			}
	        
	        /**  原来写法   传一个request
			//压缩文件名字
	        if(base_name.equals("") ||  base_name==null){
	        	base_name =UUID.randomUUID().toString().replaceAll("-","");	
	        }
	        System.out.println("名字::"+base_name);
	        
	        List<String> imgsList = new ArrayList<>();
	        //把 String 类型转化成  数组
	        String[] arrayImg = type.replaceAll(", ",",").replace("[","").replace("]","").split(",");
	        //把数组转化成 list
	        imgsList =  Arrays.asList(arrayImg);
	        //遍历list,给每个文件设置url路径,文件名字,文件类型    添加到另一个list中,进行下载时的压缩保存
	        int imgs = 1;
	        if(imgsList.size()>0){
		        for(int i=0;i<imgsList.size();i++){
		        	if(imgsList.get(i)!=null&&!imgsList.get(i).equals("")){
	        			imgfile imgfile=new imgfile();
						imgfile.setImgurl("http://a.kcway.net/assess/"+imgsList.get(i));
						imgfile.setName(i+1+"");
						imgfile.setFilelast(imgsList.get(i).substring(imgsList.get(i).lastIndexOf(".")+1,imgsList.get(i).length()));
						FileNameList.add(imgfile);	
						imgs++;
	        		}
				}
	        }
	        */
	        
	        // 把全部的文件放进文件数组中  File[]  files
			int leng = FileNameList.size();
			System.out.println(leng);
			InputStream inputStream = null;
			DataInputStream in = null;
			URL url=null;
			OutputStream os=null;
			ByteArrayOutputStream bos=null;
			try {					   
			   bos = new ByteArrayOutputStream();
			   ZipOutputStream zos = new ZipOutputStream(bos);
			   UrlFilesToZip s = new UrlFilesToZip();
			   int idx = 1;
			   for (imgfile imgfile1:FileNameList) {			    
				    byte[] bytes=null;			    
				    bytes = s.getImageFromURL(imgfile1.getImgurl());				    
				    zos.putNextEntry(new ZipEntry(imgfile1.getName()+"."+imgfile1.getFilelast()));
				    zos.write(bytes,0,bytes.length);
				    //size=size+bytes.length;
					zos.closeEntry();
				    idx++;	
			   }			
			   zos.close();
			   response.setContentType("application/force-download");// 设置强制下载不打开  
			   response.addHeader("Content-Disposition","attachment;fileName="+base_name+".zip");// 设置文件名			   			  
			   os = response.getOutputStream(); // 
			   os.write(bos.toByteArray());	               			   
			   os.close();
			   bos.close();			  
			  }catch(Exception ex) {
				   ex.printStackTrace();
				   ServletOutputStream sos = null;  
	               try {  
	                   //response.setContentType("text/html;charset=utf-8");  
	                   sos = response.getOutputStream();  
	                   sos.write(
                          "<script>alert('下载失败,请稍后下载!');</script>".getBytes("UTF-8")
                       );
	                   sos.flush();  
	               } catch (IOException e1) {  
	                   e1.printStackTrace();  
	               }finally{  
	                   if(null != sos){  
	                       try {  
	                           sos.close();  
	                       } catch (IOException e1) {  
	                           e1.printStackTrace();  
	                       }  
	                   }  
	               } 
			    }finally{
			    	if(os!=null){
			    		os.close();
			    	}
			    	if(bos!=null){
			    		bos.close();	
			    	}
			    }
	}