设为首页 收藏本站
查看: 635|回复: 0

[经验分享] org.apache.tools.zip.*和org.apache.commons.httpclient.*实现远程文件打包下载,支持中文文件名

[复制链接]

尚未签到

发表于 2017-1-11 09:18:51 | 显示全部楼层 |阅读模式
package com.kedacom.kdkk.controller.querymanager;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
public class BatchDownload extends HttpServlet {
private static List list = new ArrayList();
Date date = null;
private static int BUF_SIZE = 40480;  
private static String ZIP_ENCODEING = "GBK";  

public BatchDownload() {
super();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置编码
request.setCharacterEncoding("utf-8");
date =  new Date();
//设置下载头信息
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\""+date.getTime()+".zip\"");
//要打包下载的图片json参数
String cbxStr = request.getParameter("cbxStr");
if(cbxStr.length() > 0){
cbxStr = cbxStr.substring(0, cbxStr.length()-1);
String [] cbxs = cbxStr.split(";");
HttpClient client = new HttpClient();
GetMethod get = null;
//创建本地存储文件路径
new File("d:/vehicleImgs/"+date.getTime()+"/").mkdir();
for(int i = 0; i < cbxs.length; i ++){
try {   
//构建远程服务的图片下载路径
String cbxs2 [] = cbxs.split("z");
String vid = cbxs2[0];
String timestamp = cbxs2[1];
String imgtype = cbxs2[2].split(",")[0];
String imgName = cbxs2[3];
imgName = imgName.replace(" ", "_").replace(":", "_");
DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Long timeStamp = format1.parse(timestamp).getTime();
String imgUrl = getServletContext().getInitParameter("opticmServer");                 
//此方法的参数可自行传入,参数值为远程服务的servlet(xxx.do),返回的值为文件流对象
get = new GetMethod(imgUrl+"&contentId="+vid+"&imgType="+imgtype+"&imgOrder=0&timeStamp="+timeStamp);   
int j = client.executeMethod(get);                              
if (200 == j)//是否正确返回                                                   
{                                                               
File storeFile = new File("d:/vehicleImgs/"+date.getTime()+"/"+imgName+".jpg");
FileOutputStream output = new FileOutputStream(storeFile);  
// 得到网络资源的字节数组,并写入文件                        
output.write(get.getResponseBody());                        
output.close();      
}else{                                                               
System.out.println("no pic");                              
}                                                           
} catch ( Exception e ){                                                                  
System.out.println("Exception no pic");                                   
} finally{
get.releaseConnection();
}
}
try {
//开始压缩下载下来的本机图片
zip("d:\\vehicleImgs\\"+date.getTime()+".zip", new File("d:\\vehicleImgs\\"+date.getTime()+"\\"));
//下载zip打包后的文件
FileInputStream fis = new FileInputStream("d:\\vehicleImgs\\"+date.getTime()+".zip");
byte[] bytes=new byte[BUF_SIZE];
int r = 0;   
response.flushBuffer();
while((r=fis.read(bytes))>0) {
response.getOutputStream().write(bytes,0,r);
}
fis.close();
response.getOutputStream().close();
} catch (Exception e) {
e.printStackTrace();
}  
}
}
/**
* 压缩文件或文件夹
*  
* @param zipFileName
* @param inputFile
* @throws Exception
*/  
public void zip(String zipFileName, File inputFile) throws Exception {  
// 未指定压缩文件名,默认为"ZipFile"   
if (zipFileName == null || zipFileName.equals(""))  
zipFileName = "ZipFile";  
// 添加".zip"后缀   
if (!zipFileName.endsWith(".zip"))  
zipFileName += ".zip";  
// 创建文件夹   
File f = null;
String path = Pattern.compile("[\\/]").matcher(zipFileName).replaceAll(File.separator);  
int endIndex = path.lastIndexOf(File.separator);  
path = path.substring(0, endIndex);  
f = new File(path);
f.mkdirs();  
// 开始压缩   
{  
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName)));  
zos.setEncoding(ZIP_ENCODEING);  
compress(zos, inputFile, "");
zos.close();  
}  
}  
/**
* 压缩一个文件夹或文件对象到已经打开的zip输出流 <b>不建议直接调用该方法</b>
*  
* @param zos
* @param f
* @param fileName
* @throws Exception
*/  
public void compress(ZipOutputStream zos, File f, String fileName) throws Exception {  
if (f.isDirectory()) {  
// 压缩文件夹   
File[] fl = f.listFiles();  
zos.putNextEntry(new ZipEntry(fileName + "/"));  
fileName = fileName.length() == 0 ? "" : fileName + "/";  
for (int i = 0; i < fl.length; i++) {  
compress(zos, fl, fileName + fl.getName());  
}  
} else {  
// 压缩文件   
zos.putNextEntry(new ZipEntry(fileName));  
FileInputStream fis = new FileInputStream(f);  
this.inStream2outStream(fis, zos);  
zos.flush();
fis.close();  
zos.closeEntry();  
}  
}  
public void inStream2outStream(InputStream is, OutputStream os) throws IOException {  
BufferedInputStream bis = new BufferedInputStream(is);  
BufferedOutputStream bos = new BufferedOutputStream(os);  
int bytesRead = 0;  
for (byte[] buffer = new byte[BUF_SIZE]; ((bytesRead = bis.read(buffer, 0, BUF_SIZE)) != -1);) {  
bos.write(buffer, 0, bytesRead); // 将流写入   
}  
}  

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-326801-1-1.html 上篇帖子: java.lang.ClassCastException: org.apache.catalina.util.DefaultAnnotationProcesso 下篇帖子: 使用apache common-net包装实现tftp server
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表