Java在线打包下载

不废话上代码

import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.util.StringUtils;

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

import javax.annotation.Resource;

import javax.servlet.http.HttpServletResponse;

import java.io.*;

import java.net.URL;

import java.net.URLConnection;

import java.nio.charset.Charset;

import java.util.ArrayList;

import java.util.List;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

@Controller

@RequestMapping("/downloadZip")

@Slf4j

public class DownloadZipController {

@Resource

private XxxService xxxService ;

 

@RequestMapping("/downloadZipFile")

public String downLoadFile(HttpServletResponse response, String fileUrl, String id, ModelMap modelMap) throws Exception {

String fileName = "";

List<String> list = new ArrayList<>();

List<File> fileList = new ArrayList<>();

List<Model> listPa = xxxService .getModel(id);

if (listPa.size() > 0) {

for (int i = 0; i < listPa.size(); i++) {

list.add(fileUrl + listPa.get(i).getAttach());

fileList.add(new File(fileUrl + listPa.get(i).getAttach()));

}

if (StringUtils.isEmpty(listPa.get(0).getName())) {

fileName = "文件";

} else {

fileName = listPa.get(0).getName();

}

//响应头的设置

response.reset();

response.setContentType("application/force-download");

response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("UTF-8"), "iso-8859-1") + ".zip");

response.setContentType("application/octet-stream;charset=utf-8");

//设置压缩流:直接写入response,实现边压缩边下载

Charset charset = Charset.forName("UTF-8");

ZipOutputStream zipos = null;

OutputStream out = response.getOutputStream();

zipos = new ZipOutputStream(new BufferedOutputStream(out), charset);

//设置压缩方法

zipos.setMethod(ZipOutputStream.DEFLATED);

DataOutputStream os = null;

try {

//循环将文件写入压缩流

for (int i = 0; i < list.size(); i++) {

URL url = new URL(list.get(i));

URLConnection conn = url.openConnection();

InputStream inputStream = conn.getInputStream();

//添加ZipEntry,并ZipEntry中写入文件流

zipos.putNextEntry(new ZipEntry(fileList.get(i).getName()));

os = new DataOutputStream(zipos);

byte[] buff = new byte[1024 * 10];

int len = 0;

//循环读写

while ((len = inputStream.read(buff)) > -1) {

os.write(buff, 0, len);

}

//关闭此文件流

inputStream.close();

//关闭当前ZIP项,并将流放置到写入的位置。下一个条目。

zipos.closeEntry();

}

//释放资源

out.flush();

os.flush();

os.close();

zipos.close();

out.close();

//return null;

} catch (IOException e) {

e.printStackTrace();

} finally {

//释放资源

os.close();

zipos.close();

out.close();

}

return null;

}else{

modelMap.put("code","没有可下载的内容,如需下载请在工程资料中下载");

return "views/download";

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值