业务需求:客户需要根据选择省市县区来下载对应行政区划下的图片,且里面图片文件夹及内容建立的顺序也要是省-市-县/区-镇/街道。。。。顺序建立,
思路:存储时候按照上面行政区划顺序建立文件夹存储,下载时候根据前端传来行政区划字段进行查询和压缩下载;
百度了一堆方法,无奈个人学识尚浅,他人写的不带注释,看不懂,无奈摸索清楚后,记录此笔记。
代码:这时候前端传值url格式,文件夹的话:比如:url=河南省-xx市-xxx县,文件的话:url=河南省-xx市-xxx县.123.jpg
@GetMapping("/load")
public void resourceDownload(String url, HttpServletRequest request, HttpServletResponse response)throws Exception {
// 本地资源统一存放路径前缀
String localPath = E:/insurance/uploadPath/upload;
//压缩包名称
String zipName = "压缩包.zip";
//压缩路径和压缩包名称
FileOutputStream fos = new FileOutputStream(new File(localPath+"/"+zipName));
//拼接所要压缩的文件夹路径
String fileUrl = localPath;
String[] ss = url.split("-");
List<String> list=Arrays.asList(ss);
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String s = iterator.next();
fileUrl= fileUrl+ "/" + s;
}
//压缩
ToZIPUtil.toZip(fileUrl,fos,true);
//导出
String contentType = "application/octet-stream";
// download(request, response, 压缩包位置, 压缩包名称);
download(request, response, localPath+"/"+zipName, contentType,zipName);
//删除--根据路径删除指定的压缩包
FileUtils.deleteFile(localPath+"/"+zipName);
}
/**
* 下载
*/
public static void download(HttpServletRequest request,HttpServletResponse response, String storeName, String contentType,String realName) throws Exception {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
String downLoadPath = storeName;
long fileLength = new File(downLoadPath).length();
response.setContentType(contentType);
response.setHeader("Content-disposition", "attachment; filename="
+ new String(realName.getBytes("utf-8"), "ISO8859-1"));
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);
}
bis.close();
bos.close();
}
压缩工具:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @Author lwy
* @ClassName ToZIPUtil 压缩文件
* @Description TODO
* @Date 2019/3/25 17:39
* @Version 1.0
*/
public class ToZIPUtil {
private static final int BUFFER_SIZE = 2 * 1024;
/**
23
* 压缩成ZIP
24
* @param srcDir 压缩文件夹路径
25
* @param out 压缩文件输出流
26
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
27
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
28
* @throws RuntimeException 压缩失败会抛出运行时异常
29
*/
public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
throws RuntimeException{
long start = System.currentTimeMillis();
ZipOutputStream zos = null ;
try {
zos = new ZipOutputStream(out);
File sourceFile = new File(srcDir);
compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) +" ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils",e);
}finally{
if(zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
94
* 递归压缩方法
95
* @param sourceFile 源文件
96
* @param zos zip输出流
97
* @param name 压缩后的名称
98
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
99
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
100
* @throws Exception
101
*/
private static void compress(File sourceFile, ZipOutputStream zos, String name,
boolean KeepDirStructure) throws Exception{
byte[] buf = new byte[BUFFER_SIZE];
if(sourceFile.isFile()){
// 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
zos.putNextEntry(new ZipEntry(name));
// copy文件到zip输出流中
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1){
zos.write(buf, 0, len);
}
// Complete the entry
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();
if(listFiles == null || listFiles.length == 0){
// 需要保留原来的文件结构时,需要对空文件夹进行处理
if(KeepDirStructure){
// 空文件夹的处理
zos.putNextEntry(new ZipEntry(name + "/"));
// 没有文件,不需要文件的copy
zos.closeEntry();
}
}else {
for (File file : listFiles) {
// 判断是否需要保留原来的文件结构
if (KeepDirStructure) {
// 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
// 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
} else {
compress(file, zos, file.getName(),KeepDirStructure);
}
}
}
}
}
}
删除方法:
/**
* 删除文件
*
* @param filePath 文件
* @return
*/
public static boolean deleteFile(String filePath)
{
boolean flag = false;
File file = new File(filePath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists())
{
file.delete();
flag = true;
}
return flag;
}
补助支出,欢迎大家补充和沟通。