package cn.palmte.work.utils; import cn.palmte.work.config.Constant; import cn.palmte.work.pojo.UploadResult; import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.ResourceUtils; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.UUID; /** * 上传工具类 * * @author pengqiang * @date 2018/5/3 */ public class UploadUtil { private static final Logger LOGGER = LoggerFactory.getLogger(UploadUtil.class); /** * 允许上传的文件类型 */ private static final String[] ALLOWED_FILE_EXTENSION = { //image "jpeg","jpg", "jpg", "bmp", "gif", "png", //app "apk", "ipa", //file "xls", "xlsx", "txt", "doc", "docx", "pdf", //voice "mp3", "wma", "wav", //video "avi", "rmvb", "mp4", "mpeg", "wmv", "mkv", // "zip", "rar", "7z" }; private UploadUtil() { } /** * classpath:/static/upload/ * * @return */ public static String getDefaultUploadPath() { String staticPath = ""; try { URL url = ResourceUtils.getURL("classpath:"); //获取跟目录 File path = new File(url.getPath()); if (!path.exists()) { path = new File(""); } File upload = new File(path.getAbsolutePath(), "static/upload/"); if (!upload.exists()) { boolean mkRes = upload.mkdirs(); if (!mkRes) { LOGGER.error("mkdirs has false, path:{}", upload.getAbsolutePath()); } } staticPath = upload.getAbsolutePath(); } catch (FileNotFoundException e) { } return staticPath; } /** * 上传 */ /** */ public static UploadResult upload(MultipartFile file, String uploadPath , String uploadPrefix) { UploadResult result = new UploadResult(Constant.STATUS_FAILED); if (file == null) { result.setMsg("文件为空"); return result; } boolean isDev = false; if (StringUtils.isBlank(uploadPath)) { uploadPath = getDefaultUploadPath(); isDev = true; } //文件名 String fileName = file.getOriginalFilename(); result.setOriginName(fileName); int endIndex = fileName.lastIndexOf('.'); String prefix = fileName.substring(0, endIndex); result.setName(prefix); //文件后缀 如:png String suffix = fileName.substring(endIndex + 1); if (!Arrays.asList(ALLOWED_FILE_EXTENSION).contains(suffix)) { result.setMsg("不允许上传该类型的文件"); return result; } String uuid = UUID.randomUUID().toString().replace("-", ""); boolean ispic = isPic(suffix); String dateString = new SimpleDateFormat("yyyyMMdd").format(new Date()); //保存的新名字 String newName = prefix + "_" + DateKit.toStr(new Date(), "yyyyMMddHHmmss") + "." + suffix; result.setNewName(newName); String path = "file/" + dateString + "/" + newName; if (ispic) { path = "image/" + dateString + "/" + newName; } File dest = new File(uploadPath + "/" + path); LOGGER.info(dest.getAbsolutePath()); saveFile(file, dest); String url1 = uploadPrefix + "/" + path; LOGGER.info(url1); result.setUrl(url1); if (isDev) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); String url = basePath + uploadPrefix + "/" + path; LOGGER.info(url); result.setUrl(url); } result.setStatus(Constant.STATUS_SUCCESS); return result; } /** * 保存 */ private static void saveFile(MultipartFile source, File dest) { //判断文件父目录是否存在 if (!dest.getParentFile().exists()) { boolean res = dest.getParentFile().mkdirs(); if (!res) { LOGGER.info("mkdir has false, path: {} ", dest.getParentFile().getAbsolutePath()); } } try { //保存文件 source.transferTo(dest); } catch (IOException e) { } } /** * 判断是否是图片 */ public static boolean isPic(String suffix) { boolean ispic = false; if (StringUtils.isBlank(suffix)) { return ispic; } ispic = Arrays.asList(new String[]{"png", "jpg", "jpeg", "bmp", "gif"}).contains(suffix); return ispic; } }