压缩包上传 压缩并解压缩Rar/Zip
1.上传压缩包
package com.example.demo.controller;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.example.demo.data.Config;
import com.example.demo.data.UploadRecords;
import com.example.demo.repo.BatchRepo;
import com.example.demo.service.BatchService;
import com.example.demo.service.MultigrahService;
import com.example.demo.service.UploadRecordsService;
import com.example.demo.util.ApiTool;
import com.example.demo.util.UnZip;@RestController
@Configurable
@RequestMapping("/mul")
public class MultigraphController {private static Logger log = Logger.getLogger(MultigraphController.class);private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");@AutowiredConfig config;@AutowiredMultigrahService multigrahService;@AutowiredBatchService batchService;/*@AutowiredBatchRepo batchRepo*/;/*** 上传医疗* * @return* @throws UnsupportedEncodingException*/@SuppressWarnings({ "static-access", "unchecked" })@RequestMapping("/discern")@Scope("prototype")public String recognition(@RequestParam(value = "file") MultipartFile file,@RequestParam(value = "username") String username, @RequestParam(value = "type") String type,@RequestParam(value = "account") String account, HttpServletRequest req) throws IOException {Map<String, String> returnmap =multigrahService.recognition(file, username, type, account, req);return returnmap.get("info");}@CrossOrigin@RequestMapping("/validate")@ResponseBodypublic String validate(@RequestParam(value = "file") MultipartFile file,@RequestParam(value = "username") String username, @RequestParam(value = "type") String type,@RequestParam(value = "account") String account, HttpServletRequest req, HttpSession session)throws Exception {log.info("开始验证校验压缩包");return multigrahService.validate(file,config.getHome() + "image" + File.separator + session.getAttribute("usr"), username);}@RequestMapping("/selectzip")@ResponseBodypublic String selectzipname(@RequestParam(value = "batch_id") String batch_id,HttpServletRequest req) {String name=batchService.selectBatchname(batch_id);System.out.println(name);return name;}
}
2.录入批次
package com.example.demo.service;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import com.example.demo.data.domain.Batch;
import com.example.demo.repo.BatchRepo;
@Service
public class BatchService {@AutowiredBatchRepo batchRepo;public String saveBatch(String name,int count,String date){Batch batch=Batch.builder().name(name).count(count).startdate(date).build();batch=batchRepo.save(batch);if (batch.getId() != null && batch.getId() > 0){return batch.getId().toString();}return "error";}public String selectBatchname(String batch_id){return batchRepo.selectBatchname(batch_id);}}
3.验证并上传
package com.example.demo.service;import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import javax.servlet.http.HttpServletRequest;import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;import com.example.demo.controller.Timer;
import com.example.demo.data.Config;
import com.example.demo.data.UploadRecords;
import com.example.demo.repo.UploadRecordsRepo;
import com.example.demo.util.ApiTool;
import com.example.demo.util.Library;
import com.example.demo.util.UnZip;
import com.sun.jna.Memory;
import com.sun.jna.ptr.FloatByReference;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;@Service
public class MultigrahService {private static Logger log = Logger.getLogger(MultigrahService.class);private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");@AutowiredConfig config;@AutowiredUploadRecordsRepo uploadRecordsRepo;@AutowiredUploadRecordsService uploadRecordsService;@AutowiredBatchService batchService;public static String generate(String usr) {String string = usr + "_";for (int i = 0; i < 16; i++) {string = string + (int) (Math.random() * 10);}return string;}/**** * 转换base64* * @param multipartFile* @param imageUrl* @return* @throws Exception*/@SuppressWarnings("resource")public String changeBase64(String oldpath, String newpath, HttpServletRequest req) {try {InputStream is = new FileInputStream(oldpath);int available = is.available();byte[] bytes = new byte[available];File files = new File(newpath);if (!files.exists()) {try {files.getParentFile().mkdirs();files.createNewFile();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();return "报错:" + e.getMessage() + "," + e.toString() + "," + ErrorToLogString(e) + ",files=" + files+ "req:" + req + "path:" + newpath;}}FileOutputStream fileOutputStream = new FileOutputStream(files);is.read(bytes);fileOutputStream.write(bytes);fileOutputStream.close();delete(oldpath);is.close();String base64 = Base64.encode(bytes);base64 = base64.replace("+", "%2B");return base64;} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}return "error";}/**** * 要求验证* * @param multipartFile* @param imageUrl* @return* @throws Exception*/@SuppressWarnings("unchecked")public String validate(MultipartFile multipartFile, String imageUrl, String username) throws Exception {if (username == null || username.equals("")) {return "login";}String originalFilename = multipartFile.getOriginalFilename();long size = multipartFile.getSize();InputStream inputStream = multipartFile.getInputStream();imageUrl = imageUrl + "/";int upcount = uploadRecordsRepo.selectCount(username) + uploadRecordsRepo.selectBatchCount(username);if (upcount >= 30) {// 总数已超出20张return "maxCount";} else {String contentType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);if (!(contentType.toLowerCase()).equals("zip") && !(contentType.toLowerCase()).equals("rar")) {return "format";} else {String fileFullName = Timer.getPinYin(originalFilename);SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");Date date = new Date();String current = sdf.format(date);String DLL_PATH = config.getHome() + "dll";log.info("dll的路径" + DLL_PATH);System.setProperty("jna.library.path", DLL_PATH);if (!(contentType.toLowerCase()).equals("zip") && !(contentType.toLowerCase()).equals("rar")) {// 没用到size = size / 1024 / 1024;if (size > 8) {return "imageSize";} else {FileUtils.copyInputStreamToFile(inputStream, new File(imageUrl, fileFullName));Memory discription = new Memory(10);discription.clear();FloatByReference confidence = new FloatByReference();String oldFileUrl = imageUrl + fileFullName;log.info("源目录:::" + oldFileUrl);try {Library.eai_qt_detect(oldFileUrl, discription, confidence);} catch (Throwable e) {log.error("图片" + oldFileUrl + "出错" + e.getMessage());}String result = discription.getString(0);System.out.println(result);if (result.equals("blur")) {delete(oldFileUrl);return "imageBlur";} else if (result.equals("curl")) {delete(oldFileUrl);return "imageCurl";} else {return "success";}}} else {FileUtils.copyInputStreamToFile(inputStream, new File(imageUrl, fileFullName));String zipUrl = imageUrl + fileFullName;File dir = new File(imageUrl);imageUrl = imageUrl + current + "/";Map<String, Object> map = new HashMap<String, Object>();UnZip.unZip(zipUrl, imageUrl);String rootfolder = fileFullName.substring(0, fileFullName.lastIndexOf("."));if ((contentType.toLowerCase()).equals("rar")) {map = UnZip.zipValidate(zipUrl, contentType, imageUrl + getFileList(imageUrl, rootfolder) + "/",getFileList(imageUrl, rootfolder));} else {map = UnZip.zipValidate(zipUrl, contentType, "", "");}if (!(Boolean) map.get("count")) {// 张数限制 delete(zipUrl);deletefile(imageUrl.substring(0, imageUrl.lastIndexOf("/")));delete(zipUrl);return "zipCount";} else {if (!(Boolean) map.get("suffix")) {delete(zipUrl);deletefile(imageUrl.substring(0, imageUrl.lastIndexOf("/")));return "zipSuffix";} else {if (!(Boolean) map.get("size")) {delete(zipUrl);deletefile(imageUrl.substring(0, imageUrl.lastIndexOf("/")));return "zipSize";} else {try {// UnZip.unZip(zipUrl, imageUrl);if ((Boolean) map.get("isDirectory")) {String chineseFolder = map.get("folder").toString();String folder = Timer.getPinYin(chineseFolder);renameTo(imageUrl + chineseFolder, imageUrl + folder);List<String> list = (List<String>) map.get("list");upcount = upcount + 1;log.info("今日已上传了" + upcount + "张");if (upcount > 30) {// 总数已超出20张delete(zipUrl);deletefile(imageUrl.substring(0, imageUrl.lastIndexOf("/")));String info = "每天限制30个赔案包,今日已上传了" + (upcount - 1) + "个";return info;}int no = 0;for (String chineseString : list) {String string = Timer.getPinYin(chineseString);String prev = string.substring(0, string.lastIndexOf("."));String suf = string.substring(string.lastIndexOf(".") + 1);string = prev + no + "." + suf;log.info("new name:::" + string);renameTo(imageUrl + folder + "/" + chineseString,imageUrl + folder + "/" + string);no++;}int no2 = 0;for (String string : list) {string = Timer.getPinYin(string);String prev = string.substring(0, string.lastIndexOf("."));String suf = string.substring(string.lastIndexOf(".") + 1);string = prev + no2 + "." + suf;delete(imageUrl + folder + "/" + string);no2++;}// delete(imageUrl + folder);deletefile(imageUrl.substring(0, imageUrl.lastIndexOf("/")));return "success";} else {List<String> list = (List<String>) map.get("list");upcount = upcount + 1;log.info("今日已上传了" + upcount + "张");if (upcount >= 30) {// 总数已超出20张delete(zipUrl);deletefile(imageUrl.substring(0, imageUrl.lastIndexOf("/")));String info = "每天限制30个赔案包,今日已上传了" + (upcount - 1) + "个";return info;}int no = 0;for (String chineseString : list) {String string = Timer.getPinYin(chineseString);String prev = string.substring(0, string.lastIndexOf("."));String suf = string.substring(string.lastIndexOf(".") + 1);string = prev + no + "." + suf;log.info("new name:::" + string);System.out.println("返回" + imageUrl + chineseString);renameTo(imageUrl + chineseString, imageUrl + string);no++;}int no2 = 0;for (String string : list) {string = Timer.getPinYin(string);String prev = string.substring(0, string.lastIndexOf("."));String suf = string.substring(string.lastIndexOf(".") + 1);string = prev + no2 + "." + suf;delete(imageUrl + string);no2++;}deletefile(imageUrl.substring(0, imageUrl.lastIndexOf("/")));return "success";}} catch (Exception e) {delete(zipUrl);return "unZip";}}}}}}}}/**** * 压缩包上传* * @param multipartFile* @param imageUrl* @return* @throws Exception*/public Map<String, String> recognition(MultipartFile file, String username, String type, String account,HttpServletRequest req) throws IOException {Map<String, String> returnmap = new HashMap<String, String>();String imageUrl = config.getHome() + "image/" + username + "/";String newimageUrl = "";String fold = "";SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");Date date = new Date();String current = sdf.format(date);if (username == null || username.equals("")) {returnmap.put("info", "login");}String originalFilename = file.getOriginalFilename();originalFilename = Timer.getPinYin(originalFilename);originalFilename = originalFilename.trim().substring(originalFilename.lastIndexOf("\\") + 1);String parentname = originalFilename.substring(0, originalFilename.lastIndexOf("."));// 压缩包前缀String contentType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);// 压缩包后缀log.info(parentname + "文件后缀名" + contentType);String info = "";if (!(contentType.toLowerCase()).equals("zip") && !(contentType.toLowerCase()).equals("rar")) {} else {String zipUrl = imageUrl + originalFilename;int count = 0;try {File dir = new File(imageUrl);imageUrl = imageUrl + current + "/";Map<String, Object> map = new HashMap<String, Object>();UnZip.unZip(zipUrl, imageUrl); // 1System.out.println("解压路径:::" + imageUrl);String rootfolder = originalFilename.substring(0, originalFilename.lastIndexOf("."));if ((contentType.toLowerCase()).equals("rar")) {map = UnZip.zipValidate(zipUrl, contentType, imageUrl + getFileList(imageUrl, rootfolder) + "/",getFileList(imageUrl, rootfolder));} else {map = UnZip.zipValidate(zipUrl, contentType, "", "");}delete(zipUrl);List<String> list = (List<String>) map.get("list");List<String> imagenamelist = new ArrayList<String>();count = list.size();int no = 0;if ((Boolean) map.get("isDirectory")) {String folder = map.get("folder").toString();for (String imageChineseFullName : list) {String prev = imageChineseFullName.substring(0, imageChineseFullName.lastIndexOf("."));String suf = imageChineseFullName.substring(imageChineseFullName.lastIndexOf(".") + 1);String newimageChineseFullName = prev + no + "." + suf;renameTo(imageUrl + folder + "/" + imageChineseFullName,imageUrl + folder + "/" + newimageChineseFullName);// 重命名String imageFullName = Timer.getPinYin(newimageChineseFullName);renameTo(imageUrl + folder + "/" + newimageChineseFullName,imageUrl + folder + "/" + imageFullName);// 重命名newimageUrl = imageUrl + folder + "/";fold = folder;// wjj folder/imageFullNameno++;}} else {for (String imageChineseFullName : list) {String prev = imageChineseFullName.substring(0, imageChineseFullName.lastIndexOf("."));String suf = imageChineseFullName.substring(imageChineseFullName.lastIndexOf(".") + 1);String newimageChineseFullName = prev + no + "." + suf;System.out.println(newimageChineseFullName);renameTo(imageUrl + imageChineseFullName, imageUrl + newimageChineseFullName);// 重命名String imageFullName = Timer.getPinYin(newimageChineseFullName);newimageUrl = imageUrl + parentname + "/";fold = parentname;mkdir(newimageUrl);renameTo(imageUrl + newimageChineseFullName, newimageUrl + "/" + imageFullName);System.out.println(newimageChineseFullName + "---" + newimageUrl);no++;}}String batchdate = df.format(new Date());// 图片上传时间String batchId = batchService.saveBatch(originalFilename, list.size(), batchdate);// 第一张建模开始时间// log.info("新批次号" + batchId);int no2 = 0;for (String string : list) {int id = uploadRecordsService.selectMaxUploadId();log.info("新上传号为:::" + id + "----批次号:::" + batchId);String prevc = string.substring(0, string.lastIndexOf("."));String sufc = string.substring(string.lastIndexOf(".") + 1);String newimageChineseFullName = prevc + no2 + "." + sufc;System.out.println(newimageChineseFullName);String imageFullName = Timer.getPinYin(newimageChineseFullName);String imageName = imageFullName.substring(imageFullName.lastIndexOf("\\") + 1);String prev = imageName.substring(0, imageName.lastIndexOf("."));// 图片名前缀String suf = imageName.substring(imageName.lastIndexOf(".") + 1);// 图片名后缀log.info("imageName:::" + imageName + "----图片前缀:::" + prev);String newimageName = prev + "_" + batchId + "_" + id + "." + suf;// 文件名imagenamelist.add(newimageName);String jsonpath = newimageName.substring(0, newimageName.lastIndexOf("."));// jsonpathString imageOldPath = newimageUrl + imageName;String newimagePath = newimageUrl + newimageName;System.out.println("新路径上传" + imageFullName + "---" + imageName + "---" + newimageName);String base64 = changeBase64(imageOldPath, newimagePath, req);no2++;if (base64 == null || base64 == "") {info = "其他图上传成功," + imageFullName + "图片有误";UploadRecords up = new UploadRecords(username, "1",username + "/" + current + "/" + fold + "/" + newimageName, batchId, jsonpath,batchdate, null, "票据有误", "票据有误", type, null, account); 写入数据库uploadRecordsService.writeUploadRecords(up);} else {delete(imageOldPath);UploadRecords up = new UploadRecords(username, "1",username + "/" + current + "/" + fold + "/" + newimageName, batchId, jsonpath,batchdate, null, "未完成", "未接收", type, null, account); 写入数据库System.out.println(up.getFinishdate());String imageId = uploadRecordsService.writeUploadRecords(up);if (!imageId.equals("error")) {// 成功上传System.out.println("成功上传"); //// System.out.println(base64);String requestXML = "参数"; // 开始上传String url = "请求接口";String send = ApiTool.send(requestXML, url);send = send.replaceAll("null", "\"" + jsonpath + "\"");log.info("请求结果:::" + send);if (send.equals("2")) {uploadRecordsService.updateUploadRecordsById(null, "接收失败", "未接收", id);continue;} else {uploadRecordsService.updateUploadRecordsById(null, "接收成功", "未接收", id);continue;}}}}} catch (Exception e) {e.printStackTrace();// return "报错:" + e.getMessage() + "," + e.toString() + "," +// ErrorToLogString(e) + "req:" + req;returnmap.put("info", "error");return returnmap;}if (info != "") {returnmap.put("info", info);return returnmap;} else {returnmap.put("info", String.valueOf(count));return returnmap;}}return returnmap;}/**** * 文件复制* * @param multipartFile* @param imageUrl* @return* @throws Exception*/public static void copyFile(String src, String target) {File srcFile = new File(src);File targetFile = new File(target);try {InputStream in = new FileInputStream(srcFile);OutputStream out = new FileOutputStream(targetFile);byte[] bytes = new byte[1024];int len = -1;while ((len = in.read(bytes)) != -1) {out.write(bytes, 0, len);}in.close();out.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}System.out.println("文件复制成功");}public static void mkdir(String folderStr) {File folderFile = new File(folderStr);folderFile.mkdir();}public static void renameTo(String oldStr, String newStr) {File oldFile = new File(oldStr);File newFile = new File(newStr);oldFile.renameTo(newFile);}public static void delete(String fileStr) {File file = new File(fileStr);file.delete();}/** 读取指定路径下的文件名和目录名*/public String getFileList(String rarpath, String rootfolder) {File file = new File(rarpath);File[] fileList = file.listFiles();String fileName = "";for (int i = 0; i < fileList.length; i++) {if (fileList[i].isFile()) {// fileName = fileList[i].getName();mkdir(rarpath + rootfolder);renameTo(rarpath + fileList[i].getName(), rarpath + rootfolder + "/" + fileList[i].getName());fileName = rootfolder;System.out.println("文件:" + fileName);}if (fileList[i].isDirectory()) {fileName = fileList[i].getName();System.out.println("目录:" + fileName);}}return fileName;}/*** 删除某个文件夹下的所有文件夹和文件* * @param delpath* String* @throws FileNotFoundException* @throws IOException* @return boolean*/public static boolean deletefile(String delpath) throws Exception {try {File file = new File(delpath);// 当且仅当此抽象路径名表示的文件存在且 是一个目录时,返回 trueif (!file.isDirectory()) {file.delete();} else if (file.isDirectory()) {String[] filelist = file.list();for (int i = 0; i < filelist.length; i++) {File delfile = new File(delpath + "\\" + filelist[i]);if (!delfile.isDirectory()) {delfile.delete();System.out.println(delfile.getAbsolutePath() + "删除文件成功");} else if (delfile.isDirectory()) {deletefile(delpath + "\\" + filelist[i]);}}System.out.println(file.getAbsolutePath() + "删除成功");file.delete();}} catch (FileNotFoundException e) {System.out.println("deletefile() Exception:" + e.getMessage());}return true;}public static void delAll(String folderStr) {File folderFile = new File(folderStr);File[] files = folderFile.listFiles();if (files != null) {for (File file : files) {if (!file.isDirectory()) {file.delete();}}folderFile.delete();}}private String ErrorToLogString(Exception e) {StackTraceElement[] st = e.getStackTrace();String errorMessage = "";for (StackTraceElement stackTraceElement : st) {String exclass = stackTraceElement.getClassName();String method = stackTraceElement.getMethodName();String message = "类:" + exclass + "调用" + method + "方法时在第" + stackTraceElement.getLineNumber()+ "行代码处发生异常!\r\n";errorMessage = errorMessage + message;}if (errorMessage.length() >= 990) {errorMessage = errorMessage.substring(0, 990) + "......";}return errorMessage;}
}
4.必须下载WinRar工具并 把cmd路径修改为winrar.exe的路径
package com.example.demo.util;import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;public class UnZip {public static Map<String, Object> zipValidate(String path, String contentType, String rarurl,String folder) throws Exception {Map<String, Object> map = new HashMap<String, Object>();if ((contentType.toLowerCase()).equals("zip")) {map = traverseFolder0(path, contentType);} else if ((contentType.toLowerCase()).equals("rar")) {String foldername = folder;System.out.println("raruel:::" + rarurl + "目录名:::" + foldername);map = traverseFolder1(rarurl, foldername);}return map;}/**** * 解压缩* **/public static void unZip(String zip, String path) throws Exception {String[] cmd = { "C:/Program Files/WinRAR/WinRAR.exe", "x", "-y", zip, path };Runtime runtime = Runtime.getRuntime();try {Process p = runtime.exec(cmd);System.out.println("---" + p);BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream(), "GBK"));String line = reader.readLine();System.out.println("新纪录:::" + line);while (line != null) {line = reader.readLine();}reader.close();if (p.waitFor() != 0) {}} catch (IOException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}}/**** * ZIP应用* **/public static Map<String, Object> traverseFolder0(String path, String contentType) throws Exception {Map<String, Object> map = new HashMap<String, Object>();map.put("count", true);map.put("suffix", true);map.put("size", true);map.put("isDirectory", false);InputStream inputStream = new BufferedInputStream(new FileInputStream(path));Charset charset = Charset.forName("GBK");ZipInputStream zipInputStream = new ZipInputStream(inputStream, charset);java.util.zip.ZipEntry zipEntry;int count = 0;List<String> list = new LinkedList<String>();while ((zipEntry = zipInputStream.getNextEntry()) != null) {if (!zipEntry.isDirectory()) {count++;String name = zipEntry.getName();if (name.indexOf("/") != -1) {name = name.substring(name.lastIndexOf("/") + 1);}list.add(name);String type = name.substring(name.lastIndexOf(".") + 1);if (!type.equals("jpg") && !type.equals("JPG") && !type.equals("png") && !type.equals("PNG")&& !type.equals("gif") && !type.equals("GIF") && !type.equals("jpeg") && !type.equals("JPEG")) {// System.out.println(name+type);map.put("suffix", false);}long size = zipEntry.getSize();size = size / 1024 / 1024;if (size > 8) {map.put("size", false);}} else {map.put("isDirectory", true);String name = zipEntry.getName();name = name.substring(0, name.length() - 1);map.put("folder", name);}}zipInputStream.close();map.put("list", list);if (count > 20) {map.put("count", false);}return map;}/**** * RAR应用* **/public static Map<String, Object> traverseFolder1(String path, String foldername) {Map<String, Object> map = new HashMap<String, Object>();map.put("count", true);map.put("suffix", true);map.put("size", true);map.put("isDirectory", false);int fileNum = 0, folderNum = 0;File file = new File(path);List<String> list = new LinkedList<String>();if (file.exists()) {// LinkedList<File> list = new LinkedList<File>();File[] files = file.listFiles();for (File file2 : files) {if (!file2.isDirectory()) {System.out.println("1文件夹:" + file2.getAbsolutePath() + "---大小:::"+ getTotalSizeOfFilesInDir(new File(file2.getAbsolutePath())));long size = getTotalSizeOfFilesInDir(new File(file2.getAbsolutePath()));size = size / 1024 / 1024;if (size > 8) {map.put("size", false);}String type = file2.getAbsolutePath().substring(file2.getAbsolutePath().lastIndexOf(".") + 1);if (!type.equals("jpg") && !type.equals("JPG") && !type.equals("png") && !type.equals("PNG")&& !type.equals("gif") && !type.equals("GIF") && !type.equals("jpeg")&& !type.equals("JPEG")) {// System.out.println(name+type);map.put("suffix", false);}String name = file2.getAbsolutePath();System.out.println(name);list.add(name.substring(name.lastIndexOf("\\") + 1));fileNum++;} else {System.out.println("1文件:" + file2.getAbsolutePath() + "---大小:::"+ getTotalSizeOfFilesInDir(new File(file2.getAbsolutePath())));map.put("isDirectory", true);String name = file2.getAbsolutePath().substring(file2.getAbsolutePath().lastIndexOf(".") + 1);map.put("folder", name);list.add(file2.getAbsolutePath());folderNum++;}}map.put("isDirectory", true);// rar直接读取map.put("folder", foldername);map.put("list", list);} else {File filerar = new File(path.replace("/" + foldername + "/", ""));if (filerar.exists()) {// LinkedList<File> list = new LinkedList<File>();File[] files = filerar.listFiles();for (File file2 : files) {if (!file2.isDirectory()) {System.out.println("1文件夹:" + file2.getAbsolutePath() + "---大小:::"+ getTotalSizeOfFilesInDir(new File(file2.getAbsolutePath())));long size = getTotalSizeOfFilesInDir(new File(file2.getAbsolutePath()));size = size / 1024 / 1024;if (size > 8) {map.put("size", false);}String type = file2.getAbsolutePath().substring(file2.getAbsolutePath().lastIndexOf(".") + 1);if (!type.equals("jpg") && !type.equals("JPG") && !type.equals("png") && !type.equals("PNG")&& !type.equals("gif") && !type.equals("GIF") && !type.equals("jpeg")&& !type.equals("JPEG")) {// System.out.println(name+type);map.put("suffix", false);}String name = file2.getAbsolutePath();System.out.println(name);list.add(name.substring(name.lastIndexOf("\\") + 1));fileNum++;}}}map.put("isDirectory", false);map.put("folder", foldername);map.put("list", list);System.out.println("文件不存在!");}if (fileNum > 20) {map.put("count", false);}System.out.println("文件夹共有:" + folderNum + ",文件共有:" + fileNum);return map;}// 递归方式 计算文件的大小private static long getTotalSizeOfFilesInDir(final File file) {if (file.isFile())return file.length();final File[] children = file.listFiles();long total = 0;if (children != null)for (final File child : children)total += getTotalSizeOfFilesInDir(child);return total;}}
压缩包上传 压缩并解压缩Rar/Zip相关推荐
- window环境下运行linux解压命令,使用压缩的方式将Windows下的zip压缩包上传到Linux系统的方法解析...
我们可以使用在Windows下压缩文件夹,然后到Linux系统下解压缩的方式,完成整个上传工作. 第一步:在Windows系统下,将整个文件夹压缩成zip后缀的压缩包 方法一: 在文件夹xtemp上, ...
- zip压缩包上传linux文件名乱码
zip压缩包上传linux文件名乱码 乱码原因主要是Windows压缩的时候编码方式为gbk,而linux默认编码方式为utf8 网上有的方法说用什么yum install convmv,试了下感觉一 ...
- java 预览zip_java压缩包上传,解压,预览(利用editor.md和Jstree实现)和下载
java压缩包上传,解压,预览(利用editor.md和Jstree实现)和下载 实现功能:zip文件上传,后台自动解压,Jstree树目录(遍历文件),editor.md预览 采用Spring+Sp ...
- 【SpringBoot项目实战】图片压缩包上传、解压、存储等等一套流程教学
[SpringBoot项目实战]图片压缩包上传.解压.存储等等一套流程教学 前言 一.压缩包上传 1.接口实现 2.获取压缩包的文件名和文件路径 二.压缩包解压并保存 1.处理压缩包文件方法 解压缩步 ...
- colab上传压缩文件并解压
文章目录 前言 一.上传压缩文件 二.解压 前言 1.电脑没有GPU,想用colab跑代码试试效果 2.项目太大,不好直接上传整个文件,故上传压缩包 一.上传压缩文件 直接将压缩包拉到colab中(记 ...
- uniapp 微信小程序开发 图片上传压缩
uniapp 微信小程序开发 图片上传压缩 安卓上传图片并压缩 思路 全部代码 安卓上传图片并压缩 由于后端接口对图片的大小有限制,所以在上传图片是需要压缩处理: uni.chooseImage({c ...
- 图片上传压缩android,android 图片上传压缩常见问题分析
图片的上传与压缩是android经常需要用到的步骤,那么,如何解决上传图片oom问题呢?android 图片上传压缩常见问题分析,希望可以帮助大家更加的了解android 图片方面的困惑. 下面,是我 ...
- WPSmushProv3.7.0图片上传压缩插件-WordPress图像优化插件
简介: WP Smush Pro是一款性能最佳,易于使用的WordPress图像优化插件.该插件由WPMU DEV的专业开发人员开发,这些开发人员是许多其他出色的WordPress插件的开发人员.例如 ...
- vue+vant图片上传压缩图片大小
vue+vant图片上传压缩图片大小 可能在项目中大家都会遇到文件上传的需求,比如头像,图片等,但是太大的文件上传会给服务器造成很大大压力,那么我们就需要压缩上传的文件 其实这儿所说的压缩,就是图片重 ...
- el-upload 上传压缩图片
el-upload 上传压缩图片 <el-form-item prop="url" label="轮播图" :label-width="form ...
最新文章
- C语言梳排序Comb sort算法(附完整源码)
- 关于数据分析:你想知道的都在这里!
- c#中 uint_C#中的uint关键字
- LeetCode 1354. 多次求和构造目标数组(优先队列+逆向思考)
- TurboIM专业集成即时通讯获新宠
- 团队计划(4.27)
- 使用一般处理程序HTTPHandler下载文件
- PTA病毒序列C语言
- 选择云盾抗ddos防火墙,信息安全有保障
- 图像处理学习——色彩空间
- JS 获取当前浏览器版本,验证浏览器版本是否高于谷歌80
- Windows UI 测试
- Gitea 的简单介绍
- [Vue]实战---电商项目(项目的概述及初始化)【一】
- <table></table>表格标签的基本概念和基本属性
- App自动化元素查看工具
- 记一次由于临时变量导致的CPU使用率过高问题
- 组策略——软件限制策略(完全教程与规则示例)
- 机器视觉-相机镜头光源介绍及选型-5.选择光源
- i12 tws无线蓝牙耳机说明书