工具类方法
PhotoUtils里的方法
//上传图片
public static String uploadFile(HttpServletRequest request, MultipartFile uploadFile) throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
String res = sdf.format(new Date());
//设置的保存路径
String rootPath ="E://upload/";
//原始名称
String originalFilename = uploadFile.getOriginalFilename();
//生成文件名
String newFileName = res + UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
//创建年月日文件夹
Calendar date = Calendar.getInstance();
File dateDirs = new File(date.get(Calendar.YEAR)
+ File.separator + (date.get(Calendar.MONTH) + 1) + File.separator + (date.get(Calendar.DATE)));
//新文件
File newFile = new File(rootPath + File.separator + dateDirs + File.separator + newFileName);
//判断目标文件所在的目录是否存在
if (!newFile.getParentFile().exists()) {
//如果目标文件所在的目录不存在,则创建父目录
newFile.getParentFile().mkdirs();
}
// System.out.println(newFile);
//将内存中的数据写入磁盘
uploadFile.transferTo(newFile);
//完整的url
String fileUrl = date.get(Calendar.YEAR) + "/" + (date.get(Calendar.MONTH) + 1) + "/" + (date.get(Calendar.DATE)) + "/" + newFileName;
return fileUrl;
}
/**
* 判断上传文件大小方法
*
* @param len
* 文件长度
* @param size
* 限制大小
* @return
*/
public static boolean checkFileSize(Long len, int size) {
double fileSize = 0;
fileSize = (double) len / 1048576;
if (fileSize > size) {
return false;
}
return true;
}
Controller中的方法
//上传图片
@RequestMapping(value = "/imageUpload",method = RequestMethod.POST)
public ResponseOne imageUpload( HttpServletRequest request, MultipartFile multipartFile ) throws IOException {
ResponseOne sendVo = new ResponseOne();
String fileName ="";
//上传图片限制大小
Long len = multipartFile.getSize();
boolean isBig= PhotoUtils.checkFileSize(len,4);
if(!isBig){
sendVo.setData(null);
sendVo.setCode(1);
sendVo.setMsg("文件超出4M,请压缩后重试");
sendVo.setCount(0);
return sendVo;
}
try {
//上传实际方法
if(multipartFile.getSize()!=0) {
fileName = PhotoUtils.uploadFile(request,multipartFile);
}}
//上传失败提示
catch (IOException e) {
sendVo.setData(null);
sendVo.setCode(1);
sendVo.setMsg("上传失败");
sendVo.setCount(0);
return sendVo;
}
//上传成功
sendVo.setData(fileName);
sendVo.setMsg("上传成功");
sendVo.setCount(1);
sendVo.setCode(0);
return sendVo;
}
springBoot 的application.yml配置文件设置上传图片限制,不限制的话最大上传1M会提示报错
spring:
#文件大小 MB必须大写
# maxFileSize 是单个文件大小
# maxRequestSize是设置总上传的数据大小
servlet:
multipart:
enabled: true
max-file-size: 20MB
max-request-size: 20MB