网上找了好多资料,各取所长,感谢各路大神 话不多说上才艺
项目中上传图片到了一个文件夹中没有目录结构 (睡的大通铺),业务现在要指定目录结构然后压缩成zip提供下载
总的实现思路:
1、拷贝源文件至 目标文件夹 (作用:生成目录结构并提供压缩源文件)
2、将目标文件夹压缩成zip文件
3、下载zip文件 让前端 win.open能够下载
4、删除zip文件 和拷贝文件夹
详细代码L:
1、拷贝
String benUrl = AdminTrainServiceImpl.getBenUrl(); //获取本地url E:/tomcat/webapps/
String zipName = "YC-"+ RandomUtil.getFourRandom(5);//YC-药材
//复制文件
List<HashMap<String,Object>> imgList = trainingImgMapper.selectListByFloraId(floraIds);
for (HashMap<String,Object> hashMap : imgList){
String flieName = hashMap.get("oldUrl").toString().split(pathUrl)[1];
String newFileUrl = hashMap.get("newFileUrl").toString();
DownloadUtil.copyFile(benUrl+flieName,benUrl+"/"+zipName+"/"+newFileUrl+"/"+flieName.split("/")[2]);
}
别急一个一个来
getBenUrl: 就是一个方法,获取tomcat/webapps 的本地路径,就是E:/tomcat/webapps
public static String getBenUrl(){
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//获取服务器地址
String path = request.getServletContext().getRealPath("");
String[] webapps = path.split("webapps");
path = webapps[0] + "webapps";
return path;
}
fileName 和 newFileUrl 是我自己业务中需要的
举个例子 fileName=“img/dog.jpg” newFileUrl=“一级/二级”
这样做的目的只是为了 做一个目录结构
为copyFile() 做参数
copyFile() 是关键 复制文件夹
public static void copyFile(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
//如果文件不存在
File newFlie = new File(newPath);
if (!newFlie.exists())
{
newFlie.getParentFile().mkdirs();
}
File oldfile = new File(oldPath);
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldPath); //读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
log.error(bytesum+"");
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
}
}
catch (Exception e) {
log.error("复制单个文件操作出错",e);
}
没啥好说的
oldPath “E:/img/dog.jpg”
newPath “E:/img/一级/二级/dog.jpg”
拷贝完成
2 生成压缩包
//生成压缩包
FileOutputStream fos1 = new FileOutputStream(new File(benUrl+"/"+zipName+".zip"));
ZipUtils.toZip(benUrl+"/"+zipName, fos1,true);
new File() 里边就是你要生成的zip文件 路径
看toZip()方法
/**
* 压缩成ZIP 方法1
* @param srcDir 想要压缩的文件夹路径
* @param out 压缩文件输出流
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
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();
}
}
}
}
3 下载压缩包
//下载压缩包
DeriveUtile.deriveTable(response, benUrl+"/"+zipName+".zip",zipName+".zip");
看方法
public static void deriveTable(HttpServletResponse response, String fileName,String newFileName)throws Exception{
if(newFileName==null){
newFileName=fileName;
}
try {
InputStream inputStream = new FileInputStream(fileName);
response.setHeader("content-Type", "application/vnd.ms-excel");
OutputStream out = response.getOutputStream();
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(newFileName, "utf-8"));
int b = 0;
byte[] buffer = new byte[1000000];
while (b != -1) {
b = inputStream.read(buffer);
if (b != -1) out.write(buffer, 0, b);
}
inputStream.close();
out.close();
out.flush();
File file = new File(fileName);
file.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
fileName 是 你文件的本地路径 newFileName 是要下载的文件名
记得关闭输出流 不然文件会被占用 就删不掉了
4 删除文件
```java
//删除生成文件
DelFile.deleteDir(benUrl+"/"+zipName);
/**
* 迭代删除文件夹
* @param dirPath 文件夹路径
*/
public static void deleteDir(String dirPath)
{
File file = new File(dirPath);
if(file.isFile())
{
file.delete();
}else
{
File[] files = file.listFiles();
if(files == null)
{
file.delete();
}else
{
for (int i = 0; i < files.length; i++)
{
deleteDir(files[i].getAbsolutePath());
}
file.delete();
}
}
}
dirPath 就是要删除的文件夹 路径 ‘E:/img’
impl中总的调用:
@Override
public void imgDownload(HttpServletRequest request, HttpServletResponse response, List<Integer> floraIds) throws Exception{
String benUrl = AdminTrainServiceImpl.getBenUrl(); //获取本地url E:/tomcat/webapps/
String zipName = "YC-"+ RandomUtil.getFourRandom(5);//YC-药材
//复制文件
List<HashMap<String,Object>> imgList = trainingImgMapper.selectListByFloraId(floraIds);
for (HashMap<String,Object> hashMap : imgList){
String flieName = hashMap.get("oldUrl").toString().split(pathUrl)[1];
String newFileUrl = hashMap.get("newFileUrl").toString();
DownloadUtil.copyFile(benUrl+flieName,benUrl+"/"+zipName+"/"+newFileUrl+"/"+flieName.split("/")[2]);
}
//生成压缩包
FileOutputStream fos1 = new FileOutputStream(new File(benUrl+"/"+zipName+".zip"));
ZipUtils.toZip(benUrl+"/"+zipName, fos1,true);
//下载压缩包
DeriveUtile.deriveTable(response, benUrl+"/"+zipName+".zip",zipName+".zip");
//删除生成文件
DelFile.deleteDir(benUrl+"/"+zipName);
}
写的不太好,因为对IO流不熟 反正马马虎虎能用,
大佬路过的话可以留下宝贵意见