简介:
常见的文件打包是在服务器进行文件压缩打成tar包,然后再进行下载,最后还要删除掉临时的tar包,对于服务器来说会占用一定的资源。
以下代码是本人工作时项目所用到的,实现服务器文件边压缩打包边下载。
以下时具体的maven配置包
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.9</version>
</dependency>
import org.apache.commons.io.IOUtils;
import org.apache.comons.compress.archivers.tar.TarArchiveEntry;
imort org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
@RequestMapping(value = "tar/export/{}")
public void tarExport(HttpServletRequest request, HttpServletResponse response)throws IOException{
OutputStream os = response.getOutputStream();
//设置打包的名称
String tarName = "package.tar";
//所要打包的文件夹路径
String packagePath = " ";
response.setCharacterEncoding("UTF-8");
response.setContentType("octets/stream");
String agent = request.getHeader("USER-AGENT");
try{
if(agent.contains("MSIE") || agent.contains("Trident")){
tarName = URLEncoder.encoder(tarName, "UTF-8");
}else{
tarName = new String(tarName.getBytes("UTF-8"), "ISO-8859-1");
}
}catch(UnsupportedEncodingException e){
//采用log4j进行日志输出
logger.error(e.getMessage, e);
}
response.setHeader("Content-Disposition", "attachment;fileName=\"" + tarName + "\"");
TarArchiveOutputStream taos = null;
InputStream is = null;
try{
taos = new TarArchiveOutputStream(os);
String[] fileNameArray = new File(packagePath).list();
for(String fileName : fileNameArray){
File file = new File(packagePath + File.separator + fileName);
TarArchiveEntry entry = new TarArchiveEntry(fileName);
entry.setSize(file.length());
taos.putArchiveEntry(entry);
is = new FileInputStream(file);
//这里采用IOUtils工具类,将输入流写到输出流中
IOUtils.copy(is, taos);
//inputStream创建于for循环内部,所以需要再循环结束时,将其关闭
is.close();
taos.closeArchiveEntry();
}
}catch(Exception e){
logger.error(e.getMessage, e);
}finally{
//推荐使用try-with-resource 方式进行连接的关闭
if(taos != null){
taos.flush();
taos.close();
}
if(os != null){
os.flush();
os.close();
}
}
}
本文章系博主原创,尊重博主辛劳成果,转载请注明出处,谢谢。