关于springmvc下服务器文件打包成zip格式下载功能

2016年09月21日 11:22:14 toxic_guantou 阅读数:5731更多

个人分类: 技术点存储
 
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/toxic_guantou/article/details/52605920

近期,项目要求把服务器存储的上传文件,批量下载到本地.参考网上资料,实现了服务器文件打包成压缩文件然后down到本地功能.
具体代码实现:
1、在服务器端创建一个临时zip格式文件
2、用jdk自带的API将服务器所有文件输入到zip文件中
3、将zip文件下载到本地,并删除服务器端zip文件

@RequestMapping(value = "/downloadZip.do")
public String downloadFiles(String tcLwIds, HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<File> files = new ArrayList<File>();
File Allfile = new File(request.getSession().getServletContext().getRealPath("/") + "upload/");
if (Allfile.exists()) {
File[] fileArr = Allfile.listFiles();
for (File file2 : fileArr) {
files.add(file2);
}
} String fileName = UUID.randomUUID().toString() + ".zip";
// 在服务器端创建打包下载的临时文件
String outFilePath = request.getSession().getServletContext().getRealPath("/") + "upload/"; File fileZip = new File(outFilePath + fileName);
// 文件输出流
FileOutputStream outStream = new FileOutputStream(fileZip);
// 压缩流
ZipOutputStream toClient = new ZipOutputStream(outStream);
// toClient.setEncoding("gbk");
zipFile(files, toClient);
toClient.close();
outStream.close();
this.downloadFile(fileZip, response, true);
return null;
}

将服务器文件存到压缩包中

public static void zipFile(List<File> files, ZipOutputStream outputStream) throws IOException, ServletException {
try {
int size = files.size();
// 压缩列表中的文件
for (int i = 0; i < size; i++) {
File file = (File) files.get(i);
zipFile(file, outputStream);
}
} catch (IOException e) {
throw e;
}
}
public static void zipFile(File inputFile, ZipOutputStream outputstream) throws IOException, ServletException {
try {
if (inputFile.exists()) {
if (inputFile.isFile()) {
FileInputStream inStream = new FileInputStream(inputFile);
BufferedInputStream bInStream = new BufferedInputStream(inStream);
ZipEntry entry = new ZipEntry(inputFile.getName());
outputstream.putNextEntry(entry); final int MAX_BYTE = 10 * 1024 * 1024; // 最大的流为10M
long streamTotal = 0; // 接受流的容量
int streamNum = 0; // 流需要分开的数量
int leaveByte = 0; // 文件剩下的字符数
byte[] inOutbyte; // byte数组接受文件的数据 streamTotal = bInStream.available(); // 通过available方法取得流的最大字符数
streamNum = (int) Math.floor(streamTotal / MAX_BYTE); // 取得流文件需要分开的数量
leaveByte = (int) streamTotal % MAX_BYTE; // 分开文件之后,剩余的数量 if (streamNum > 0) {
for (int j = 0; j < streamNum; ++j) {
inOutbyte = new byte[MAX_BYTE];
// 读入流,保存在byte数组
bInStream.read(inOutbyte, 0, MAX_BYTE);
outputstream.write(inOutbyte, 0, MAX_BYTE); // 写出流
}
}
// 写出剩下的流数据
inOutbyte = new byte[leaveByte];
bInStream.read(inOutbyte, 0, leaveByte);
outputstream.write(inOutbyte);
outputstream.closeEntry(); // Closes the current ZIP entry
// and positions the stream for
// writing the next entry
bInStream.close(); // 关闭
inStream.close();
}
} else {
throw new ServletException("文件不存在!");
}
} catch (IOException e) {
throw e;
}
}

下载文件

 public void downloadFile(File file,HttpServletResponse response,boolean isDelete) {
try {
// 以流的形式下载文件。
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("UTF-8"),"ISO-8859-1"));
toClient.write(buffer);
toClient.flush();
toClient.close();
if(isDelete)
{
file.delete(); //是否将生成的服务器端文件删除
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}

单个文件的下载

@RequestMapping(value="/singleDownload.do")
public String singleDownload(String fileName, HttpServletRequest request,
HttpServletResponse response)throws Exception{
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName="+ fileName);
String realPath = request.getSession().getServletContext().getRealPath("/");
String path = realPath+"upload/";
File file = new File(path+ File.separator + fileName);
downloadFile(file, response, false);
return null;
}

关于springmvc下服务器文件打包成zip格式下载功能的更多相关文章

  1. java批量下载,将多文件打包成zip格式下载

    现在的需求的: 根据产品族.产品类型,下载该产品族.产品类型下面的pic包: pic包是zip压缩文件: t_product表: 这些包以blob形式存在另一张表中: t_imagefile表: 现在 ...

  2. java批量将多文件打包成zip格式

    public void createzip(){ List<File> nFileList = new ArrayList<File>(); nFileList.add(new ...

  3. java将文件打包成ZIP压缩文件的工具类实例

    package com.lanp; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ja ...

  4. java实现将文件压缩成zip格式

    以下是将文件压缩成zip格式的工具类(复制后可以直接使用): zip4j.jar包下载地址:http://www.lingala.net/zip4j/download.php package util ...

  5. SpringMVC+Ajax实现文件批量上传和下载功能实例代码

    需求: 文件批量上传,支持断点续传. 文件批量下载,支持断点续传. 使用JS能够实现批量下载,能够提供接口从指定url中下载文件并保存在本地指定路径中. 服务器不需要打包. 支持大文件断点下载.比如下 ...

  6. 多个文件下载打包生成zip格式下载

    这个多个文件下载生成zip格式必须先引用一个ICSharpCode.SharpZipLib.dll. 代码如下  //将多个文件打包成压缩文件zip格式下载         protected voi ...

  7. Java实现文件自动打包成zip并下载的代码

      import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java. ...

  8. 文件打包为zip格式文件下载

    整个思路是这样的: 1.查询数据库中的文件流放到datatable中2.循环datatable将文件流一个个生成文件,放到对应的文件夹中,3.下载某个文件夹下的所有文件a.循环这个文件夹下的所有文件, ...

  9. php 下载图片并打包成Zip格式压缩包

    前言:最近公司有个需要下载多个图片并打包成压缩包的需求,下面来看看具体是怎么做的 1.没什么说的,懒得说啥,直接看代码 /** * 下载图片并生成压缩包 * @param $data 图片数组,一维 ...

随机推荐

  1. HTML/JSP中一些单书名号标签的用途<%-- --%><!-- --><%@ %><%! %><% %><%= %>

    注释 <%-- --%>是(JSP)隐式注释,不会在页面显示的注释 <!-- -->是(Html)显示注释,会在JSP页面显示 关于注释还有单行隐式注释//和多行隐式注释/* ...

  2. django启动创建用户失败

    a django应用启动 b 访问127.0.0.1:8000,报错信息如下,原因为没有这个用户需要创建下用户 c 创建用户过程中报错原因是因为添加了app需要告诉django,这个 模型发生了改变, ...

  3. 【C#】arcface人脸识别使用问题分析

    arcface上线了新版 正好有空 赶紧下载体验了一番 凡是过程中也遇到一些问题 1.初始化 [DllImport("libarcsoft_face_engine.dll", En ...

  4. leetcode个人题解——#5 Container with most water

    class Solution { public: string longestPalindrome(string s) { int length = s.length(); ) return s; ; ...

  5. 如何做好FAE工作及FAE职位发展

    此文较长,是作者对于半导体FAE职业的一些总结,码字不容易,耐心的阅读,欢迎点赞. 曾经认识一位做电源研发的工程师,转行在一家代理商做FAE,做了一年半以后,就提出了离职请求,他老板问他是什么原因,他 ...

  6. str和repr

    在Python2.6和Python3.0以及更早的版本中,在交互式模式下的输出本质上是使用repr,因此对于一些浮点数运算,会显示很多位: 4 / 5.0 #0.8000000000000004 但是 ...

  7. No Route to Host from master/192.168.2.131 to master:9000 failed on socket t

    host里边添加的ip地址与当前的ip地址(ifconfig可以查看)不一致,修改当前ip地址就可以了.

  8. ACM 第七天

    水题 B - Minimum’s Revenge There is a graph of n vertices which are indexed from 1 to n. For any pair ...

  9. PART1 一些想法

    其实我一直是一个后知后觉的人,这点也是我过了好久才发现的问题,之所以晚发现自己这个毛病,是因为后知后觉==,这有点像是个悖论或者是笑话,但的确是真实存在于我的身上.其实当初为啥来这个学校选计算机的专业 ...

  10. java的参数传递

    1按值传递:传递的是原始值的副本,而不是原始值的内存地址 基本数据类型是传原始值的副本 class Test02 { public static void main(String[] args) { ...