java 将服务器的图片打包下载成.zip ,通过浏览器下载。

public void download(HttpServletRequest request, HttpServletResponse response){
 
            try {
                String downloadFilename = "中文.zip";//文件的名称
                downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");//转换中文否则可能会产生乱码
                response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
                response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);// 设置在下载框默认显示的文件名
                ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
                String[] files = new String[]{"http://xxxx/xx.jpg","http://xxx/xx.jpg"};
                for (int i=0;i<files.length;i++) {
                    URL url = new URL(files[i]);
                   zos.putNextEntry(new ZipEntry(i+".jpg"));
                   //FileInputStream fis = new FileInputStream(new File(files[i])); 
                   InputStream fis = url.openConnection().getInputStream();  
                   byte[] buffer = new byte[1024];    
                   int r = 0;    
                   while ((r = fis.read(buffer)) != -1) {    
                       zos.write(buffer, 0, r);    
                   }    
                   fis.close();  
                  } 
                zos.flush();    
                zos.close();
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
    }

判断服务器上是否有相应的问文件:

String filePath="http://117.51.149.90/videos/"+paramsBean.getEventId()+".mp4";
			  URL url = new URL(filePath);
			 HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
	         String message = urlcon.getHeaderField(0);
			 if (StringUtils.hasText(message) && message.startsWith("HTTP/1.1 404")) {
                                //不存在
				 map.put("videoPath", "");
				 }else{
                                 //存在
					 map.put("videoPath", filePath);
	             }

判断服务器的方法存在问题:

由于是http地址就相当于每次都要请求服务器  极大的消耗性能和影响查询时间

优化:直接获取地址在服务器那边文件夹直接查询文件是否存在

String filePath = "/home/dc2-user/audi/apache-tomcat-8.5.35/webapps/images/"+fileName+"/" + paramsBean.getEventId() + ".mp4";
			
			File file =new File(filePath);
			if(file.exists()) {
				map.put("videoPath", filePath);
			}else {
				map.put("videoPath", "");
			}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值