1.controller
/**
* 下载文件
* @return
*/
@RequestMapping(method = RequestMethod.POST,value="/downloadFile")
public void downloadFile(HttpServletRequest request,HttpServletResponse response){
try {
//页面参数
String riskname = request.getParameter("riskname");
String licenseplate = request.getParameter("licenseplate");
String downloadurl = request.getParameter("downloadurl");
if(StringUtils.isBlank(riskname) || StringUtils.isBlank(licenseplate) || StringUtils.isBlank(downloadurl)){
return ;
}
String str[] = downloadurl.split(",");//切分前端以以逗号隔开的文件路径
//设置请求相关参数
request.setCharacterEncoding("UTF-8");
//缓冲流
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
List<String> attachmentList = new ArrayList<String>();
if(null!=str && str.length>0){
for(int i= 0;i< str.length;i++){
attachmentList.add( str[i]);
}
}
//获取项目路径,可自行定义
String rootPath = request.getSession().getServletContext().getRealPath("/");
//压缩文件名,需要自定义
String zipFileName =riskname+"_"+licenseplate+"_"+DateUtils.formatDate(new Date(), "yyyyMMdd")+"_"+DateUtils.formatDate(new Date(), "HHmmss")+".zip";
//压缩文件
DownloadFileUtil downUtil = new DownloadFileUtil();//压缩工具
String zipPath = rootPath+"/zip/";//压缩路径
downUtil.createZipFile(zipFileName, attachmentList,zipPath);
String downLoadPath = zipPath + zipFileName;//下载路径
try {
long fileLength = new File(downLoadPath).length();
response.setContentType("application/octet-stream;charset=UTF-8");
String fileName = URLEncoder.encode(zipFileName, "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.setHeader("Content-Length", String.valueOf(fileLength));
//写入缓冲流
bis = new BufferedInputStream(new FileInputStream(downLoadPath));//从下载路径写入到缓存流中
//输出到页面
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
logger.error("下载文件失败!",e);
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
// 下载完成后删除文件
try{
downUtil.deleteFile(zipPath);
}catch (Exception e) {
logger.error("删除文件失败!",e.getMessage());
}
} catch (Exception e) {
logger.error("压缩文件失败!",e);
}
}
2.工具类 DownloadFileUtil
package com.ra.ctrl.riskmanage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
public class DownloadFileUtil {
/**
* 创建压缩文件,返回压缩文件名
*
* @param fileName
* @param dataList
* @param rootPath
* @return
*/
public String createZipFile(String zipFileName, List<String> fileList, String zipPath) {
ZipOutputStream zos = null;
try {
String savePath = zipPath;//压缩包路径
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
//压缩文件
zos = new ZipOutputStream(new FileOutputStream(savePath + zipFileName));
zos.setEncoding("UTF-8");
zipFile(fileList, zos);
return savePath;//如果需求,可以没有返回值
} catch (Exception e) {
e.printStackTrace();
} finally {
if (zos != null) {
try {
zos.flush();
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 压缩文件
*
* @param datas
* @param zos
* @throws IOException
*/
private void zipFile(List<String> datas, ZipOutputStream zos) throws IOException {
if (datas != null && datas.size() > 0) {
for (int i = 0; i < datas.size(); i++) {
String at = datas.get(i);
//文件读取到文件流中
URL url = new URL(at);
URLConnection connection = url.openConnection();
InputStream fis = connection.getInputStream();
//压缩文件名称
String zippath = File.separatorChar + (at.substring(at.lastIndexOf("/") + 1, at.length()));
zos.putNextEntry(new ZipEntry(zippath));//压缩文件名
//把流中文件写到压缩包
byte[] buffer = new byte[1024];
int r = 0;
while ((r = fis.read(buffer)) != -1) {
zos.write(buffer, 0, r);
}
fis.close();
}
}
}
/**
* 删除文件
*
* @param filePath
* @return
*/
public boolean deleteFile(String filePath) {
boolean flag = false;
File file = new File(filePath);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (filePath.endsWith(File.separator)) {
temp = new File(filePath + tempList[i]);
} else {
temp = new File(filePath + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
deleteFile(filePath + "/" + tempList[i]);// 先删除文件夹里面的文件
deleteFile(filePath + "/" + tempList[i]);// 再删除空文件夹
flag = true;
}
}
return flag;
}
}