CMS后台有上传多个图片的需求,多个图片上传也一样麻烦。就想做个上传压缩包服务端解压上传的东西。
页面
使用h5的上传api
/*
*
* name: 上传字段标示
postUrl: 文件数据处理URL
onClientAbort: 读取操作终止时调用
onClientError: 出错时调用
onClientLoad: 读取操作成功时调用
onClientLoadEnd: 无论是否成功,读取完成时调用。通常在onload和onerror后调用
onClientLoadStart: 读取将要开始时调用
onClientProgress: 数据在读取过程中周期性调用
onServerAbort: post操作结束时调用
onServerError: 错误发生时调用
onServerLoad: post操作成功时调用
onServerLoadStart: post数据将要开始时调用
onServerProgress: 数据正在被post的过程中周期性调用
onServerReadyStateChange: 一个javascript功能对象无论任何时候readyState属性变化时调用。callback由用户界面现成调用。
*
*
* */
$("#uploadZip").html5Uploader({
url: "rest/material/uploadZip",
onSuccess: function (e, file, response) {
var res = JSON.parse(response);
if (res == "200") {
$.sticky("已经成功上传并且存入原始素材库!");
swal("SUCCESS!", "已经成功上传并且存入原始素材库!", "success");
} else {
$.sticky("压缩格式错误或压缩过程出现错误");
swal("OMG!", "压缩包有错误请重新压缩并重新上传 = = !!!", "error");
}
},
onClientLoad: function () {
$.sticky("文件读取成功! ! !");
},
onClientLoadEnd: function () {
$.sticky("文件上传完成! ! !");
},
onClientLoadStart: function () {
$.sticky("文件将要开始读取! ! !");
},
onClientProgress: function () {
},
onServerError: function () {
console.log(11111111 + "========")
},
onServerProgress: function () {
$.sticky("文件正在上传! ! !");
}
});
用了一些美化过的弹窗控件
引入js就行了。
后台模板之前常用ACE的。
扣下来改吧改吧。
服务端
服务端用的Java写的。
@Transactional
@RequestMapping(value = "uploadZip", method = RequestMethod.POST)
public Map<String, Object> uploadZip(HttpServletRequest request) throws Exception {
Map<String, Object> result = new HashMap<>();
User user = GrantedFilter.threadLocal.get();
final Integer userId = user.getId();
Uploader uploader = new Uploader(request);
// 解压
final File[] fileList = uploader.uploadMaterialZip();
// 有时候压缩会出问题 Mac 和 Windows
if (fileList.length < 1 || fileList.length>1?fileList[1].isDirectory():fileList[0].isDirectory()) {
File f = null;
try {
f = new File(fileList[0].getParent());
deleteFile(f);
} catch (Exception e) {
}
result.put("code", "400");
return result;
} else {
threadPoolTaskExecutor.execute(new Runnable() {
@Override
public void run() {
String temp = fileList[0].getParent();
for (File file : fileList) {
if (file.getName().endsWith(".gif")||file.getName().endsWith(".GIF")) {
UFileRequest uFileRequest = new UFileRequest();
String gifKey = RandomStringUtils.randomAlphanumeric(32) + ".gif";
uFileRequest.setBucketName(SysConfigDao.getValue(SysConfig.otherConfig, "ufile_bucket"));
uFileRequest.setFilePath(file.getPath());
uFileRequest.setKey(gifKey);
uFileAPI.putFile(uFileRequest);
String url = uFileAPI.getDownloadUrl(uFileRequest, 0, false);
MaterialRaw materialRaw = new MaterialRaw();
materialRaw.setTag("3");
materialRaw.setGifurl(url);
materialRaw.setCreateAt(new Date());
materialRaw.setStatus("t");
materialRaw.setChannl("r");
try {
materialRaw.setMd5(MD5Util.getMd5ByFile(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
materialRaw.setSize((int) file.length());
materialRaw.setCreateBy(userId);
try {
materialRaw.setTitle(file.getName().substring(0, file.getName().lastIndexOf(".gif")));
} catch (Exception e) {
materialRaw.setTitle(file.getName().substring(0, file.getName().lastIndexOf(".GIF")));
}
materialRawDao.save(materialRaw);
}
file.delete();
}
File f = new File(temp);
deleteFile(f);
}
});
}
result.put("code", "200");
return result;
}
解压的Util类
public File[] uploadMaterialZip() throws Exception {
originalName = request.getHeader("X-File-Name");
type = FileUtil.getFileExt(originalName);
if (!".zip".equals(type.toLowerCase())) {
throw new BadRequestException("格式错误!");
}
if (request.getContentLength() / 1024000 > 100) {
throw new BadRequestException("文件太大!");
}
fileName = Util.RunTimeSequence() + type;
path = DateUtil.zipDateFormat(new Date()) + File.separator + fileName;
File file = new File(savePath + File.separator + path);
file.getParentFile().mkdirs();
try (InputStream is = request.getInputStream();
FileOutputStream fos = new FileOutputStream(file)) {
IOUtils.copy(is, fos);
size = file.length();
}
String str = savePath + File.separator + System.currentTimeMillis();
File dir = new File(str);
if (!dir.exists() || !dir.isDirectory()) {
dir.mkdirs();
}
String temp = savePath + File.separator + DateUtil.zipDateFormat(new Date()) + File.separator;
// 加压的工具类
DeCompressUtil.deCompress(savePath + File.separator + path, str, temp);
File gifFile = new File(str);
File[] fileList = gifFile.listFiles();
if (fileList.length<1){
gifFile.delete();
}
return fileList;
}
解压
package com.an.core.utils.zip;
import com.an.core.exception.BadRequestException;
import de.innosystec.unrar.Archive;
import de.innosystec.unrar.rarfile.FileHeader;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;
import java.io.File;
import java.io.FileOutputStream;
public class DeCompressUtil {
/**
* 解压zip格式压缩包
* 对应的是ant.jar
*/
private static void unzip(String sourceZip, String destDir, String temp) throws Exception {
try {
Project p = new Project();
Expand e = new Expand();
e.setProject(p);
e.setSrc(new File(sourceZip));
e.setOverwrite(false);
e.setDest(new File(destDir));
/*
ant下的zip工具默认压缩编码为UTF-8编码,
而winRAR软件压缩是用的windows默认的GBK或者GB2312编码
所以解压缩时要制定编码格式
*/
try {
e.setEncoding("GBK");
e.execute();
} catch (Exception e1) {
e.setEncoding("UTF-8");
e.execute();
}
File zipFile = new File(sourceZip);
File zipPath = new File(temp);
zipFile.delete();
zipPath.delete();
} catch (Exception e) {
throw new BadRequestException(e);
}
}
/**
* 解压rar格式压缩包。
* 对应的是java-unrar-0.3.jar,但是java-unrar-0.3.jar又会用到commons-logging-1.1.1.jar
*/
private static void unrar(String sourceRar, String destDir, String temp) throws Exception {
Archive a = null;
FileOutputStream fos = null;
try {
a = new Archive(new File(sourceRar));
FileHeader fh = a.nextFileHeader();
while (fh != null) {
if (!fh.isDirectory()) {
//1 根据不同的操作系统拿到相应的 destDirName 和 destFileName
String compressFileName = fh.getFileNameString().trim();
String destFileName = "";
String destDirName = "";
//非windows系统
if (File.separator.equals("/")) {
destFileName = destDir + compressFileName.replaceAll("\\\\", "/");
destDirName = destFileName.substring(0, destFileName.lastIndexOf("/"));
//windows系统
} else {
destFileName = destDir + compressFileName.replaceAll("/", "\\\\");
destDirName = destFileName.substring(0, destFileName.lastIndexOf("\\"));
}
//2创建文件夹
File dir = new File(destDirName);
if (!dir.exists() || !dir.isDirectory()) {
dir.mkdirs();
}
//3解压缩文件
fos = new FileOutputStream(new File(destFileName));
a.extractFile(fh, fos);
fos.close();
fos = null;
}
fh = a.nextFileHeader();
}
a.close();
a = null;
} catch (Exception e) {
throw e;
} finally {
if (fos != null) {
try {
fos.close();
fos = null;
} catch (Exception e) {
e.printStackTrace();
}
}
if (a != null) {
try {
a.close();
a = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 解压缩
*/
public static void deCompress(String sourceFile, String destDir, String temp) throws Exception {
//保证文件夹路径最后是"/"或者"\"
char lastChar = destDir.charAt(destDir.length() - 1);
if (lastChar != '/' && lastChar != '\\') {
destDir += File.separator;
}
//根据类型,进行相应的解压缩
String type = sourceFile.substring(sourceFile.lastIndexOf(".") + 1);
if (!".zip".equals(type.toLowerCase())) {
DeCompressUtil.unzip(sourceFile, destDir, temp);
} else if (type.equals("rar")) {
DeCompressUtil.unrar(sourceFile, destDir, temp);
} else {
}
}
}
删除文件夹下面的所有内容
/**
* 删除文件夹所有的文件和文件夹
*
* @param file
*/
public static void deleteFile(File file){
if(file.isFile()){
file.delete();
return;
}
if(file.isDirectory()){
File[] childFile = file.listFiles();
if(childFile == null || childFile.length == 0){
file.delete();
return;
}
for(File f : childFile){
RecursionDeleteFile(f);
}
file.delete();
}
}
之前有找过一个Demo
希望对你有帮助 😂😂😂。
欢迎光临我的个人博客