java zip下载_java 文件打包下载

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.tools.zip.ZipEntry;

import org.apache.tools.zip.ZipOutputStream;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

/**

* 报告管理--- 需要上传的文件

* @author lyq

*

*/

@Controller

@RequestMapping("/files")

public class FilesController {

/**

* 下载 报告资料(这个需要打包下载所有的 所以单独列出来)

* 这个路径还没有改动

* @param request

* @param response

* @param reportId

* @return

* @throws IOException

*/

@RequestMapping(value="/downReport")

public String downReport(HttpServletRequest request,HttpServletResponse response) throws IOException{

String tmpFileName = "ceshi.zip";

byte[] buffer = new byte[1024];

String strZipPath ="D://"+tmpFileName;

try {

ZipOutputStream out = new ZipOutputStream(new FileOutputStream(

strZipPath));

// 需要同时下载的两个文件a.txt ,b.txt

String []filePath={"D://conf.xml","D://login.htm"};

File[] file1 =new File[filePath.length] ;

for(int i=0;i

file1[i]=new File(filePath[i]);

}

for (int i = 0; i < file1.length; i++) {

FileInputStream fis = new FileInputStream(file1[i]);

out.putNextEntry(new ZipEntry(file1[i].getName()));

//设置压缩文件内的字符编码,不然会变成乱码

out.setEncoding("GBK");

int len;

// 读入需要下载的文件的内容,打包到zip文件

while ((len = fis.read(buffer)) > 0) {

out.write(buffer, 0, len);

}

out.closeEntry();

fis.close();

}

out.close();

this.downloadFile(strZipPath,response);

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

public void downloadFile(String fileName,HttpServletResponse response){

response.setCharacterEncoding("utf-8");

response.setContentType("multipart/form-data");

response.setHeader("Content-Disposition", "attachment;fileName=report.zip");

try {

File file=new File(fileName);

System.out.println(file.getAbsolutePath());

InputStream inputStream=new FileInputStream(file);

OutputStream os=response.getOutputStream();

byte[] b=new byte[1024];

int length;

while((length=inputStream.read(b))>0){

os.write(b,0,length);

}

inputStream.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值