通过流下载&批量下载

通过流的方式,实现文件下载,可支持批量下载:

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Component
@Slf4j
public class FileHelper {
private static String rootPath = "";
private static String nextPath = "";
@Autowired
private ConfigureService configureService;

public void setFilePath() {
// 接入厂家对象
Configure configure = new Configure();
configure.setName("根路径");
configure.setStatus("启用");
List<Configure> page = configureService.queryExport(configure);
for (Configure cc : page) {
if (cc.getConfKey().equals("infoattachment.location")) {
rootPath = cc.getConfVal();
} else {
nextPath = cc.getConfVal();
}
}
}
// @Autowired

/**
* 保存文件到临时目录
*
* @param multipartFile
* @return
*/
public InfoAttachment saveTemp(MultipartFile multipartFile) {
setFilePath();
InfoAttachment attachment = FileUtil.saveFile(rootPath, nextPath,
multipartFile);
return attachment;
}

/**
* 下载附件
*/
/*public ResponseEntity<byte[]> download(HttpServletRequest request, HttpServletResponse response, String relativePath, String downloadName)
throws Exception {
setFilePath();
String path = rootPath+File.separator + relativePath;
HttpHeaders headers = new HttpHeaders();
ResponseEntity<byte[]> entity = null;

Date startDate = new Date();
System.out.println("文件" + path + "下载开始===========" + startDate);

File file = new File(path);

if (file.exists()) {

FileInputStream in=null;
try {
in=new FileInputStream(file);

byte[] bytes = new byte[in.available()];

//处理IE下载文件的中文名称乱码的问题
String header = request.getHeader("User-Agent").toUpperCase();
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
downloadName = URLEncoder.encode(downloadName, "utf-8");
downloadName = downloadName.replace("+", "%20"); //IE下载文件名空格变+号问题
} else {
downloadName = new String(downloadName.getBytes(), "iso-8859-1");
}

in.read(bytes);

headers.add("Content-Disposition", "attachment;filename="+downloadName);
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
entity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);

System.out.println("文件下载输出成功!!!!!=====用时:" + TimeUtil.calLastedTime(startDate) + "毫秒");

} catch (Exception e) {
System.out.println("文件下载失败");
}finally {
if(in!=null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}else {
System.out.println("文件" + path + "不存在");
}

return entity;
}*/

/**
* 通过流下载
* @param request
* @param response
* @param relativePath
* @param downloadName
* @throws Exception
*/
public boolean download(HttpServletRequest request, HttpServletResponse response, String relativePath, String downloadName)
throws Exception {
boolean isSuccess=true;
setFilePath();
String path="";
if(!StringUtil.isEmpty(rootPath)){
path = rootPath + File.separator + relativePath;
}else {
path=relativePath;
}
Date startDate = new Date();
log.info("文件" + path + "下载开始===========" + startDate);
File file = new File(path);
if (file.exists()) {
InputStream in = null;
ServletOutputStream outputStream = null;
try {
in = new FileInputStream(file);
//处理IE下载文件的中文名称乱码的问题
String header = request.getHeader("User-Agent").toUpperCase();
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
downloadName = URLEncoder.encode(downloadName, "utf-8");
downloadName = downloadName.replace("+", "%20"); //IE下载文件名空格变+号问题
} else {
downloadName = new String(downloadName.getBytes(), "iso-8859-1");
}
byte[] bytes = new byte[1024];
int len = 0;
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.addHeader("Content-Disposition",
"attachment;filename=" + downloadName);
outputStream = response.getOutputStream();
if (file.length() == 0) {
outputStream.write(in.available());
} else {
while ((len = in.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
}
}
log.info("文件下载输出成功!!!!!=====用时:" + TimeUtil.calLastedTime(startDate) + "毫秒");
} catch (Exception e) {
isSuccess=false;
log.error("文件下载失败");
} finally {
if (in != null || outputStream != null) {
try {
in.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
isSuccess=false;
log.info("文件" + path + "不存在");
}
return isSuccess;
}

/**
* 通过zip压缩的方式下载批量文件
*
* @param request
* @param response
* @param relativePath
* @param downloadName
* @throws Exception
*/
public boolean downloadByZip(HttpServletRequest request, HttpServletResponse response, String relativePath, String downloadName) throws IOException {
setFilePath();
relativePath=relativePath.replace(rootPath+"/","");
String path = rootPath+File.separator + relativePath;
boolean flag = false;
Date startDate = new Date();
log.info("文件" + path + "下载开始===========" + startDate);
File file = new File(path);

if (file.exists()) {
DataOutputStream os = null;
try {
//处理IE下载文件的中文名称乱码的问题
String header = request.getHeader("User-Agent").toUpperCase();
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
downloadName = URLEncoder.encode(downloadName, "utf-8");
downloadName = downloadName.replace("+", "%20"); //IE下载文件名空格变+号问题
} else {
downloadName = new String(downloadName.getBytes(), "iso-8859-1");
}
//设置返回头信息
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.addHeader("Content-Disposition",
"attachment;filename=" + "data.zip");
ZipOutputStream zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
zipos.setMethod(ZipOutputStream.DEFLATED);
zipos.putNextEntry(new ZipEntry(downloadName));
os = new DataOutputStream(zipos);
InputStream is = new FileInputStream(file);
byte[] b = new byte[1024];
int length = 0;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
zipos.closeEntry();
log.info("文件下载输出成功!!!!!=====用时:" + TimeUtil.calLastedTime(startDate) + "毫秒");
flag = true;
} catch (Exception ex) {
log.error("文件下载失败");
} finally {
os.flush();//必须强制刷新
}
} else {
log.info("文件" + path + "不存在");
}
return flag;
}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值