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
希望對你有幫助 ??????。
歡迎光臨我的個人博客