================================
©Copyright 蕃薯耀 2020-01-09
https://www.cnblogs.com/fanshuyao/
一、文件上传:
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.szpl.gtkj.bean.FileBean; import com.szpl.gtkj.bean.Result; import com.szpl.gtkj.exception.ValidationException; import com.szpl.gtkj.util.DateUtils; import com.szpl.gtkj.util.JsonUtil; @RestController @RequestMapping("/file") public class FileController { private static Logger log = Logger.getLogger(FileController.class); @RequestMapping("/uploadFiles") public Result uploadFiles(HttpServletRequest request, HttpServletResponse response, @RequestParam("files") MultipartFile[] multipartFiles) throws FileNotFoundException, IOException, ValidationException{ ListfileBeans = this.saveFiles(request, response, multipartFiles); log.info("fileBeans = " + JsonUtil.obj2String(fileBeans)); return Result.ok(fileBeans); } @RequestMapping("/getDirPathByUploadFiles") public Result getNetPathByUploadFiles(HttpServletRequest request, HttpServletResponse response, @RequestParam("files") MultipartFile[] multipartFiles) throws Exception{ List fileBeans = this.saveFiles(request, response, multipartFiles); if(fileBeans == null || fileBeans.size() < 1) { throw new ValidationException("文件上传失败,请重试"); } FileBean fileBean = fileBeans.get(0); String absolutePath = fileBean.getAbsolutePath(); String dirPath = absolutePath.substring(0, absolutePath.lastIndexOf("/")); log.info("dirPath = " + JsonUtil.obj2String(dirPath)); return Result.ok(dirPath); } /** * 通用文件上传 * @param request HttpServletRequest * @throws IOException * @throws FileNotFoundException */ public List saveFiles(HttpServletRequest request, HttpServletResponse response, @RequestParam("files") MultipartFile[] multipartFiles) throws FileNotFoundException, IOException{ List files = new ArrayList (); String dirPath = request.getParameter("dirPath");//文件的绝对目录(c:/a/b/)或者相对路径的目录(aa/bb/) String isEncode = request.getParameter("isEncode"); String isRename = request.getParameter("isRename");//默认是true,使用uuid改名,要使用原来的名称,则isRename="false" String isDirWrap = request.getParameter("isDirWrap");//多文件上传包裹一层文件夹 String isDirWrapSuffix = request.getParameter("isDirWrapSuffix");//包裹文件夹后缀 String isUseTime = request.getParameter("isUseTime"); String useTimePattern = request.getParameter("useTimePattern"); Date date = new Date(); if("true".equalsIgnoreCase(isEncode)){ dirPath = URLDecoder.decode(dirPath, "UTF-8"); } String defaultDir = "H:/scan/gtkjCghj/"; if(!StringUtils.isBlank(dirPath)){ dirPath = dirPath.trim(); if(dirPath.indexOf(":") > -1){ defaultDir = dirPath; }else{ defaultDir = defaultDir + dirPath; } String lastCode = defaultDir.substring(defaultDir.length() - 1); if(!"/".equals(lastCode)){ defaultDir = defaultDir + "/"; } }else{ defaultDir += "temp_dir/"; } if("true".equalsIgnoreCase(isDirWrap)) { String pattern = DateUtils.YEAR_TO_MILLION; String dirWrap = DateUtils.format(date, pattern); if(!StringUtils.isBlank(isDirWrapSuffix)) { dirWrap += isDirWrapSuffix; } defaultDir += (dirWrap + "/"); } File dir = new File(defaultDir); if(!dir.exists()){ dir.mkdirs(); } log.info("文件上传保存的硬盘路径:"+ defaultDir); if(multipartFiles != null && multipartFiles.length > 0) { FileBean fileBean = null; for (MultipartFile multipartFile : multipartFiles) { String originalName = multipartFile.getOriginalFilename(); if(StringUtils.isBlank(originalName)) { throw new ValidationException("文件名称不能为空,请检查"); } if(!StringUtils.isBlank(originalName)){ originalName = new String(originalName.getBytes(), "UTF-8"); } fileBean = new FileBean(); String uuid = UUID.randomUUID().toString().replaceAll("-", ""); String suffix = ""; if(originalName.lastIndexOf(".") > -1) { suffix = originalName.substring(originalName.lastIndexOf(".")); fileBean.setSuffix(suffix); }else { fileBean.setSuffix(""); } if("false".equalsIgnoreCase(isRename) || "0".equals(isRename)){ fileBean.setFileName(originalName); }else{ if(!StringUtils.isBlank(isUseTime)){ String pattern = DateUtils.YEAR_TO_MILLION; if(!StringUtils.isBlank(useTimePattern)){ pattern = useTimePattern.trim(); } uuid = DateUtils.format(date, pattern); } fileBean.setFileName(uuid + suffix); } fileBean.setOriginalName(originalName); fileBean.setFileSize(multipartFile.getSize()/1024 + "KB"); fileBean.setOriginalFileSize(multipartFile.getSize()); fileBean.setFileType(multipartFile.getContentType()); String absolutePath = defaultDir + fileBean.getFileName(); fileBean.setAbsolutePath(absolutePath); FileCopyUtils.copy(multipartFile.getBytes(), new FileOutputStream(absolutePath)); files.add(fileBean); //logger.info("=====multipartFile file name = "+ originalName); //logger.info("=====multipartFile file name last = "+ fileBean.getFileName()); //logger.info("=====multipartFile file type = "+ fileBean.getFileType()); log.info("文件上传成功。fileBean = "+ JsonUtil.obj2String(fileBean)); } }else { throw new ValidationException("系统未检测到有上传文件,请检查"); } return files; } }
二、文件类bean
public class FileBean { /** * 文件名 */ private String fileName; /** * 原始文件名 */ private String originalName; /** * 文件大小(KB) */ private String fileSize; /** * 原始文件大小 */ private long originalFileSize; /** * 文件类型 */ private String fileType; /** * 后缀 */ private String suffix; /** * 绝对路径 */ private String absolutePath; /** * 对象参数 */ private Object data; public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getOriginalName() { return originalName; } public void setOriginalName(String originalName) { this.originalName = originalName; } public String getFileSize() { return fileSize; } public void setFileSize(String fileSize) { this.fileSize = fileSize; } public long getOriginalFileSize() { return originalFileSize; } public void setOriginalFileSize(long originalFileSize) { this.originalFileSize = originalFileSize; } public String getFileType() { return fileType; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public void setFileType(String fileType) { this.fileType = fileType; } public String getAbsolutePath() { return absolutePath; } public void setAbsolutePath(String absolutePath) { this.absolutePath = absolutePath; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } }
三、日期工具类:
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.apache.commons.lang.StringUtils; public class DateUtils { public final static String DATE = "yyyy-MM-dd"; public final static String DATE_SLASH = "yyyy/MM/dd"; public final static String DATE_CHINESE = "yyyy年MM月dd日"; public final static String DATE_TIME = "yyyy-MM-dd HH:mm:ss"; public final static String DATE_TIME_HOURS = "yyyy-MM-dd HH"; public final static String DATE_TIME_MINUTES = "yyyy-MM-dd HH:mm"; public final static String DATE_TIME_SLASH = "yyyy/MM/dd HH:mm:ss"; public final static String DATE_TIME_CHINESE = "yyyy年MM月dd日 HH时mm分ss秒"; public final static String DATE_TIME_MILLION = "yyyy-MM-dd HH:mm:ss:SSS"; public final static String YEAR = "yyyy"; public final static String YEAR_TO_MONTH = "yyyyMM"; public final static String YEAR_TO_DATE = "yyyyMMdd"; public final static String YEAR_TO_SECOND = "yyyyMMddHHmmss"; public final static String YEAR_TO_MILLION = "yyyyMMddHHmmssSSS"; public final static String ZERO_TIME = " 00:00:00"; public final static String ZERO_TIME_MILLION = " 00:00:00:000"; public final static String ZERO_TIME_WITHOUT_HOURS = ":00:00"; public final static String ZERO_TIME_WITHOUT_MINUTES = ":00"; /** * 字符串转成日期、时间格式 * @param dateString 日期字符串 * @param pattern 格式化类型,默认为yyyy-MM-dd,其它使用DateUtils.xxx * @return * @throws ParseException */ public static Date parse(String dateString, String pattern) throws ParseException{ if(StringUtils.isBlank(dateString)){ return null; }else{ dateString = dateString.trim(); if(StringUtils.isBlank(pattern)){ pattern = DATE; } SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); return simpleDateFormat.parse(dateString); } } /** * 字符串转成日期(yyyy-MM-dd)格式 * @param dateString 日期字符串 * @return Date * @throws ParseException */ public static Date parseDate(String dateString) throws ParseException{ return parse(dateString, null); } /** * 字符串转成时间(yyyy-MM-dd HH:mm:ss)格式 * @param dateString 日期字符串 * @return * @throws ParseException */ public static Date parseDateTime(String dateString) throws ParseException{ if(StringUtils.isBlank(dateString)){ return null; }else{ dateString = dateString.trim(); if(dateString.length() == DATE_TIME_HOURS.length()){ return parse(dateString, DATE_TIME_HOURS); }else if(dateString.length() == DATE_TIME_MINUTES.length()){ return parse(dateString, DATE_TIME_MINUTES); }else if(dateString.length() == DATE_TIME_MILLION.length()){ return parse(dateString, DATE_TIME_MILLION); }else{ return parse(dateString, DATE_TIME); } } } /** * 时间转字符串 * @param date 时间 * @param pattern 格式化类型,默认为yyyy-MM-dd HH:mm:ss,其它使用DateUtils.xxx * @return */ public static String format(Date date, String pattern){ if(date == null){ return ""; }else{ if(StringUtils.isBlank(pattern)){ pattern = DATE_TIME; } SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); return simpleDateFormat.format(date); } } /** * 时间转日期字符串(yyyy-MM-dd) * @param date 时间 * @return */ public static String formatDate(Date date){ return format(date, DATE); } /** * 时间转日期字符串(yyyy-MM-dd HH:mm:ss) * @param date 时间 * @return */ public static String formatDateTime(Date date){ return format(date, null); } /** * 将日期格式转换成时间(yyyy-MM-dd HH:mm:ss)格式 * @param dateString 日期字符串 * @return */ public static String dateToDateTime(String dateString){ if(StringUtils.isBlank(dateString)){ return ""; }else{ dateString = dateString.trim(); if(dateString.length() == DATE.length()){ return dateString + ZERO_TIME; }else if(dateString.length() == DATE_TIME_HOURS.length()){ return dateString + ZERO_TIME_WITHOUT_HOURS; }else if(dateString.length() == DATE_TIME_MINUTES.length()){ return dateString + ZERO_TIME_WITHOUT_MINUTES; }else if(dateString.length() == DATE_TIME_MILLION.length()){ return dateString.substring(0, DATE_TIME.length()); }else{ return dateString; } } } /** * 将日期格式转换成时间(时分秒毫秒)格式 * @param dateString 日期字符串 * @return */ public static String dateToDateTimeMillion(String dateString){ if(StringUtils.isBlank(dateString)){ return ""; }else{ dateString = dateString.trim(); return dateString + ZERO_TIME_MILLION; } } /** * 将时间字(yyyy-MM-dd HH:mm:ss)符串转换成日期(yyyy-MM-dd)格式 * @param dateTimeString 时间字符串 * @return String */ public static String dateTimeToDate(String dateTimeString){ if(StringUtils.isBlank(dateTimeString)){ return ""; }else{ dateTimeString = dateTimeString.trim(); if(dateTimeString.length() >= DATE.length()){ return dateTimeString.substring(0, DATE.length()); }else{ return dateTimeString; } } } /** * 将时间(yyyy-MM-dd HH:mm:ss)转换成日期(yyyy-MM-dd) * @param dateTime 时间 * @return Date * @throws ParseException */ public static Date dateTimeToDate(Date dateTime) throws ParseException{ if(dateTime == null){ return null; }else{ return parseDate(formatDate(dateTime)); } } /** * 获取当前时间(yyyy-MM-dd HH:mm:ss) * @return Date */ public static Date now(){ return new Date(); } /** * 获取当前时间(yyyy-MM-dd HH:mm:ss) * @return Date */ public static Date dateTime(){ return new Date(); } /** * 获取当前时间(yyyy-MM-dd HH:mm:ss) * @return Date */ public static Date getDateTime(){ return dateTime(); } /** * 获取当前日期(yyyy-MM-dd) * @return Date * @throws ParseException */ public static Date date() throws ParseException{ return dateTimeToDate(new Date()); } /** * 获取当前日期(yyyy-MM-dd) * @return Date * @throws ParseException */ public static Date getDate() throws ParseException{ return date(); } /** * 日期加减天数 * @param date 日期,为空时默认当前时间,包括时分秒 * @param days 加减的天数 * @return * @throws ParseException */ public static Date dateAdd(Date date, int days) throws ParseException{ if(date == null){ date = new Date(); } Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, days); return cal.getTime(); } /** * 日期加减多少月 * @param date 日期,为空时默认当前时间,包括时分秒 * @param months 加减的月数 * @return * @throws ParseException */ public static Date monthAdd(Date date, int months) throws ParseException{ if(date == null){ date = new Date(); } Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.MONTH, months); return cal.getTime(); } /** * 时间比较 *如果date大于compareDate返回1,小于返回-1,相等返回0
* @param date * @param compareDate * @return * @throws ParseException */ public static int dateCompare(Date date, Date compareDate) throws ParseException{ Calendar cal = Calendar.getInstance(); Calendar compareCal = Calendar.getInstance(); cal.setTime(date); compareCal.setTime(date); return cal.compareTo(compareCal); } /** * 获取两个日期相差的天数,不包含今天 * @param startDate * @param endDate * @return * @throws ParseException */ public static int dateBetween(Date startDate, Date endDate) throws ParseException{ Date dateStart = parse(format(startDate, DATE), DATE); Date dateEnd = parse(format(endDate, DATE), DATE); return (int)((dateEnd.getTime() - dateStart.getTime()) / 1000/60/60/24); } /** * 获取两个日期相差的天数,包含今天 * @param startDate * @param endDate * @return * @throws ParseException */ public static int dateBetweenIncludeToday(Date startDate, Date endDate) throws ParseException{ return dateBetween(startDate, endDate) + 1; } @SuppressWarnings("unused") public static void main(String[] args) throws Exception { //System.out.println(dateToDatetime("2018-08-17")); //System.out.println(dateToDatetimeMillion("2018-08-17")); Date date = new Date(); //System.out.println(parse("2018-08-17", null)); //System.out.println(parseDate("2018-08-17")); //System.out.println(parseDate("2018-08-17 11:40")); //System.out.println(parseDateTime("2018-08-17 11:40")); //System.out.println(parseDateTime("2018-08-17 11:40:20")); //System.out.println(parseDateTime("2018-08-17 11:40:20:169")); //System.out.println(format(parseDateTime("2018-08-17 11:40:20:069"), DATE_TIME_MILLION)); //System.out.println(format(date, null)); //System.out.println(formatDate(date)); //System.out.println(formatDateTime(date)); //System.out.println(dateTimeToDate("2018-08-17 11:40")); //System.out.println(dateTimeToDate("2018-08-17")); //System.out.println(dateTimeToDate("2018-08-17 11")); //System.out.println(dateTimeToDate(date)); //System.out.println(formatDate(dateTimeToDate(date))); //System.out.println(formatDateTime(dateTimeToDate(date))); /* System.out.println(dateToDateTime("2018-08-17")); System.out.println(dateToDateTime("2018-08-17 12")); System.out.println(dateToDateTime("2018-08-17 13:10")); System.out.println(dateToDateTime("2018-08-17 14:10:20")); System.out.println(dateToDateTime("2018-08-17 15:10:20:158")); */ System.out.println(monthAdd(null, 12)); } }
四、返回结果工具类
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.szpl.gtkj.util.JsonUtil; public class Result { public static final String SUCCESS = "操作成功。"; public static final String FAILURE = "操作失败!"; private boolean result; private String msg; private Object datas; private Result() {} public static Result ok() { return Result.ok(SUCCESS); } public static Result ok(String msg) { return Result.ok(msg, null); } public static Result ok(Object datas) { return Result.ok(SUCCESS, datas); } public static Result ok(String msg, Object datas) { Result result = new Result(); result.setResult(true); result.setMsg(msg); result.setDatas(datas); return result; } public static Result fail() { return Result.fail(FAILURE); } public static Result fail(String msg) { return Result.fail(msg, null); } public static Result fail(Object datas) { return Result.fail(FAILURE, datas); } public static Result fail(String msg, Object datas) { Result result = new Result(); result.setResult(false); result.setMsg(msg); result.setDatas(datas); return result; } public boolean isResult() { return result; } public void setResult(boolean result) { this.result = result; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getDatas() { return datas; } public void setDatas(Object datas) { this.datas = datas; } public static void main(String[] args) { System.out.println(JsonUtil.obj2String(Result.ok())); System.out.println(JsonUtil.obj2String(Result.ok("haha"))); System.out.println(JsonUtil.obj2String(Result.ok("haha", "aaa"))); Mapmap = new HashMap (); map.put("aa", "111"); map.put("bb", "22"); map.put("ccc", "33"); System.out.println(JsonUtil.obj2String(Result.ok("haha", map))); List list = new ArrayList (); list.add("aaaaaaaa"); list.add("bbbbbb"); list.add("cccccccccccc"); list.add("ddddddddddd"); System.out.println(JsonUtil.obj2String(Result.ok("haha", list))); System.out.println(JsonUtil.obj2String(Result.fail())); System.out.println(JsonUtil.obj2String(Result.fail("失败了"))); System.out.println(JsonUtil.obj2String(Result.fail(list))); System.out.println(JsonUtil.obj2String(Result.fail("失败了", map))); } }
(如果你觉得文章对你有帮助,欢迎捐赠,^_^,谢谢!)
================================
©Copyright 蕃薯耀 2020-01-09
https://www.cnblogs.com/fanshuyao/