Java tutorial
/* * The MIT License (MIT) * * Copyright (c) 2014-2017 d05660@163.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.cloud.mblog.utils; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.lang3.StringUtils; import org.cloud.mblog.model.ImageData; import org.cloud.mblog.model.ResponseMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.UUID; /** * Created by d05660ddw on 2017/5/4. */ public class FileUtil { private static final Logger logger = LoggerFactory.getLogger(FileUtil.class); private static final String FILE_UPLOAD_DIR = "/uploads/"; private static final String IMAGE = "images/"; private static final String THUMBNAIL = "thumb/"; private static final String FILE_DATE_DIR_FMT = "yyyy/MM"; private static final String FILE_UPLOAD_SUB_IMG_DIR_FMT = "yyyyMMdd_HHmmss_SSS"; private static final String ALLOWEXT = "jpg,gif,bmp,jpeg,png"; // ? private static final long MAX_FILE_SIZE = 1024 * 1024 * 10; // ??? private static final String LOCALROOT = PropertiesUtil.getConfigBykey("uploadPath"); private static final String URLROOT = PropertiesUtil.getConfigBykey("urlPath"); /** * * * @param finalPath * @return boolean */ private static boolean makeDirs(String finalPath) { File fullFolder = new File(finalPath); if (!fullFolder.exists()) { if (!fullFolder.mkdirs()) { return false; } } return true; } /** * ? * * @param * @return */ private static String getTempRelativePath() { // ?? String finalPath = LOCALROOT + FILE_UPLOAD_DIR + "temp"; return makeDirs(finalPath) ? FILE_UPLOAD_DIR + "temp" : ""; } /** * ? * * @param path * @return */ private static String getImageRelativePath(String path) { // ?? path = path.endsWith("/") ? path : path + "/"; String finalPath = LOCALROOT + FILE_UPLOAD_DIR + path; return makeDirs(finalPath) ? FILE_UPLOAD_DIR + path : ""; } /** * @param date localtime * @return */ private static String getImageRelativePathByDate(LocalDateTime date) { // ???? DateTimeFormatter formatter = DateTimeFormatter.ofPattern(FILE_DATE_DIR_FMT); String datePath = IMAGE + date.format(formatter); return getImageRelativePath(datePath); } /** * @param date localtime * @return */ private static String getThumbRelativePathByDate(LocalDateTime date) { // ???? DateTimeFormatter formatter = DateTimeFormatter.ofPattern(FILE_DATE_DIR_FMT); String datePath = THUMBNAIL + date.format(formatter); return getImageRelativePath(datePath); } private static String getDateTypeFileName(LocalDateTime date, String suffix) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(FILE_UPLOAD_SUB_IMG_DIR_FMT); return date.format(formatter) + "." + suffix; } private static String getUUIDFileName(String suffix) { return UUID.randomUUID().toString() + "." + suffix; } private static String getWidFileName(String suffix) { return IdWorker.getSingletonId() + "." + suffix; } private static String getImageUrlPathByDate(LocalDateTime date) { return URLROOT + getImageRelativePathByDate(date); } private static String getThumbUrlPathByDate(LocalDateTime date) { return URLROOT + getThumbRelativePathByDate(date); } /** * Ckeditor? * * @param request * @return */ public static String processUploadPostForCkeditor(HttpServletRequest request) { LocalDateTime now = LocalDateTime.now(); String realFolder = LOCALROOT + getImageRelativePathByDate(now); String urlPath = getImageUrlPathByDate(now); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(new File(realFolder)); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); servletFileUpload.setFileSizeMax(MAX_FILE_SIZE); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Iterator<String> fileNameIter = multipartRequest.getFileNames(); try { while (fileNameIter.hasNext()) { MultipartFile mr = multipartRequest.getFile(fileNameIter.next()); String sourceFileName = mr.getOriginalFilename(); if (StringUtils.isNotBlank(sourceFileName)) { String fileType = sourceFileName.substring(sourceFileName.lastIndexOf(".") + 1); if (ALLOWEXT.contains(fileType)) { String filename = getDateTypeFileName(now, fileType); File targetFile = new File(realFolder + File.separator + filename); logger.info("Upload file path: " + targetFile.getAbsolutePath()); mr.transferTo(targetFile); return urlPath + "/" + filename; } else { logger.error("?: " + fileType); return ""; } } } } catch (IOException e) { logger.error("error", e); } return ""; } /** * ? * * @param avatar_file * @param request * @param x * @param y * @param width * @param height * @return */ public static ResponseMessage processCropPost(MultipartFile avatar_file, HttpServletRequest request, float x, float y, float width, float height) { LocalDateTime now = LocalDateTime.now(); String realFolder = LOCALROOT + getThumbRelativePathByDate(now); String urlPath = getThumbUrlPathByDate(now); // MIMEtype String type = avatar_file.getContentType(); if (type == null || !type.toLowerCase().startsWith("image/")) { return new ResponseMessage("????", null); } String sourceFileName = avatar_file.getOriginalFilename(); String fileType = sourceFileName.substring(sourceFileName.lastIndexOf(".") + 1); String fileName = getDateTypeFileName(now, fileType); String fullUrl = urlPath + "/" + fileName; // File targetFile = new File(realFolder, fileName); // ? try { if (!targetFile.exists()) { InputStream is = avatar_file.getInputStream(); ImageUtil.cutAndScale(ImageIO.read(is), targetFile, (int) x, (int) y, (int) width, (int) height, 500, 300); is.close(); } } catch (Exception e) { logger.error("error", e); return new ResponseMessage("" + e.getMessage(), null); } return new ResponseMessage("?", fullUrl); } /** * ? * * @param file * @return */ public static ImageData uploadSingleFile(MultipartFile file, HttpServletRequest request, Boolean haveThumb) { if (!file.isEmpty()) { LocalDateTime now = LocalDateTime.now(); String imageRelativeFolder = getImageRelativePathByDate(now); String thumbRelativeFolder = getThumbRelativePathByDate(now); String sourceFileName = file.getOriginalFilename(); String fileType = sourceFileName.substring(sourceFileName.lastIndexOf(".") + 1); String fileName = getWidFileName(fileType); File targetFile = new File(LOCALROOT + imageRelativeFolder + File.separator + fileName); try { file.transferTo(targetFile); logger.info("Upload file path: " + targetFile.getAbsolutePath()); if (haveThumb) { File thumbFile = new File(LOCALROOT + thumbRelativeFolder + File.separator + fileName); ImageUtil.zoomImage(targetFile, thumbFile, 300); } return new ImageData(fileName, file.getSize(), imageRelativeFolder, thumbRelativeFolder); } catch (Exception e) { logger.error("error", e); } } return null; } /** * * * @param files * @return */ public static List<ImageData> uploadMultipleFiles(MultipartFile[] files, HttpServletRequest request) { List<ImageData> arr = new ArrayList<>(); for (MultipartFile file : files) { arr.add(uploadSingleFile(file, request, true)); } return arr; } /** * * * @param file ?? * @param request http * @return */ public static String uploadCommonFile(MultipartFile file, HttpServletRequest request) { if (!file.isEmpty()) { String commonRelativeFolder = getTempRelativePath(); String sourceFileName = file.getOriginalFilename(); String fileType = sourceFileName.substring(sourceFileName.lastIndexOf(".") + 1); String fileName = getWidFileName(fileType); File targetFile = new File(LOCALROOT + commonRelativeFolder + File.separator + fileName); try { file.transferTo(targetFile); logger.info("Upload file path: " + targetFile.getAbsolutePath()); return targetFile.getAbsolutePath(); } catch (Exception e) { logger.error("error", e); } } return null; } /** * ? * * @param fileName * @return */ public static boolean delete(String fileName) { File file = new File(fileName); if (!file.exists()) { logger.error(":" + fileName + "??"); return false; } else { if (file.isFile()) return deleteFile(fileName); else return deleteDirectory(fileName); } } /** * ? * * @param fileName * @return */ private static boolean deleteFile(String fileName) { File file = new File(fileName); // if (file.exists() && file.isFile()) { if (file.delete()) { logger.warn("Delete " + fileName + " successful?"); return true; } else { logger.error("Delete " + fileName + " fail?"); return false; } } else { logger.error("Delete Single File" + fileName + " fail!"); return false; } } /** * ? * * @param dir * @return */ private static boolean deleteDirectory(String dir) { // dir? if (!dir.endsWith(File.separator)) dir = dir + File.separator; File dirFile = new File(dir); // dir?? if ((!dirFile.exists()) || (!dirFile.isDirectory())) { logger.error("" + dir + "??"); return false; } boolean flag = true; // ? File[] files = dirFile.listFiles(); if (files != null) { for (File file : files) { // ? if (file.isFile()) { flag = deleteFile(file.getAbsolutePath()); if (!flag) break; } // ? else if (file.isDirectory()) { flag = deleteDirectory(file.getAbsolutePath()); if (!flag) break; } } } if (!flag) { logger.error("?"); return false; } // ? if (dirFile.delete()) { logger.warn("" + dir + "??"); return true; } else { return false; } } }