最近项目用到这两个功能,总结一下,直接上代码:
文件压缩工具类
public class FileUtil {
private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
/**
* 压缩文件或文件夹
* @param zipFileName 存放压缩文件的绝对路径
* @param inputFile 文件或文件夹对象
* @throws Exception
*/
public static void zip(String zipFileName, File inputFile) throws Exception {
logger.info("压缩中......");
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
zipFileName));
zip(out, inputFile, inputFile.getName());
out.close(); // 输出流关闭
logger.info("压缩完成......");
}
private static void zip(ZipOutputStream out, File f, String base
) throws Exception { // 方法重载
try{
if (f.isDirectory()) {
File[] fl = f.listFiles();
if (fl.length == 0) {
out.putNextEntry(new ZipEntry(base + "/")); // 创建zip压缩进入点base
}
for (int i = 0; i < fl.length; i++) {
zip(out, fl[i], base + "/" + fl[i].getName()); // 递归遍历子文件夹
}
} else {
out.putNextEntry(new ZipEntry(base)); // 创建zip压缩进入点base
FileInputStream in = new FileInputStream(f);
int b;
while ((b = in.read()) != -1) {
out.write(b); // 将字节流写入当前zip目录
}
in.close(); // 输入流关闭
}
}catch(IOException e)
{
e.printStackTrace();
throw new Exception("压缩失败");
}
}
/**
* 将指点文件进行压缩
* @param zipFileName 压缩存放绝对路径
* @param fileList 文件集合需要压缩的文件,不能是文件夹
* @throws IOException
*/
public static void zipMutipleFiles(String zipFileName, List<File> fileList) throws IOException
{
if(fileList.size()<0) return;
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
zipFileName));
for (int i = 0; i < fileList.size(); i++)
{
out.putNextEntry(new ZipEntry(fileList.get(i).getName())); // 创建zip压缩进入点base
FileInputStream in = new FileInputStream(fileList.get(i));
int b;
while ((b = in.read()) != -1) {
out.write(b); // 将字节流写入当前zip目录
}
in.close(); // 输入流关闭
fileList.get(i).delete();
}
out.close();
}
}
controller类:
@Controller
public class FileController {
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
@RequestMapping(value = "/file")
public String home(){
return "File";
}
@ResponseBody
@RequestMapping("/file/downLoad")
public void fileDown(HttpServletRequest request, HttpServletResponse response){
byte[] buffer = new byte[1024];
FileInputStream fileInputStream = null;
BufferedInputStream bufferedInputStream = null;
BufferedOutputStream outputStream = null;
try {
/*--------------------对文件进行压缩--------------------------------------------*/
//需要压缩的文件,填写自己实际要压缩的文件
String zipFile = "C:\\kkweb\\zip\\2020015";
File file1 = new File(zipFile);
//压缩文件存放路径与压缩文件名称
String zipPath = "C:\\kkweb\\999.zip";
FileUtil.zip(zipPath, file1);
/*--------------------对文件进行下载--------------------------------------------*/
//下载刚刚压缩生成的zip文件
File file = new File(zipPath);
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment;filename=" +
new String(file.getName().getBytes("GB2312"), "ISO8859-1"));
fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(fileInputStream);
outputStream = new BufferedOutputStream(response.getOutputStream());
int i = bufferedInputStream.read(buffer);
while (i != -1) {
outputStream.write(buffer, 0, buffer.length);
outputStream.flush();
i = bufferedInputStream.read(buffer);
}
}catch (Exception e) {
System.out.println("下载失败");
}finally {
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
if (bufferedInputStream != null) {
try {
bufferedInputStream.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
}
}
前台html页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件下载</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<script type="text/javascript">
$(function() {
$("#download").click(function(){
window.location.href="/file/downLoad";
/* $.ajax({
url: "/file/downLoad",//url地址
type: "post",//发起请求的方式
async: false,
success:function(data) {
alert("下载成功")
},
error:function(){
alert('网络错误,请稍后再试!');
}
})*/
})
})
</script>
<body>
<h1>文件下载</h1>
<input id="download" type="button" value="下载文件"/>
</body>
</html>
总结:
刚开始打算使用ajax进行文件下载的,但是发现怎么都下载不了,网上查询了一番,说是因为ajax请求只是个“字符型”的请求,即请求的内容是以文本类型存放的。文件的下载是以二进制形式进行的,虽然可以读取到返回的response,但只是读取而已,是无法执行的。于是果断换成了
window.location.href="/file/downLoad";
这种方式。