3 回答

TA贡献1895条经验 获得超7个赞
拦截这个异常:
@ControllerAdvice
public class ExceptionProcess {
// 对这个异常的统一处理,返回值 和Controller的返回规则一样
@ExceptionHandler(MultipartException.class)
public String handleAll(Throwable t){
// TODO do sth
return "view";
}
}

TA贡献2065条经验 获得超14个赞
楼主最后是怎么解决的?我知道这个问题是设置了限制大小之后file穿不过去controller,在表单传过去的时候就被拦截抛异常了,我尝试过2楼的方法拦截了这个异常统一处理,但是控制台将这个异常处理了两次,不明白问题在哪。求助!!
源码:
Controller:
@RequestMapping(value = "/upload",method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestParam("test") MultipartFile file) {
String result = fs.upload(file);
return result;
}
Service:
@Service
public class fileServiceImp implements fileService {
@Override
public String upload(MultipartFile file) {
//判断文件是否为空
if (file.isEmpty()) { return "文件为空"; }
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//获取文件类型
String filetype = file.getContentType();
//获取文件大小
long size = file.getSize();
// 文件上传后的路径
String filePath = "/Users/ho/Documents/CMS/src/main/resources/file_temp/";
// 解决中文问题,liunx下中文路径,图片显示问题
fileName = UUID.randomUUID() + suffixName;
File dest = new File(filePath + fileName);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
//上传
file.transferTo(dest);
//获取当前时间
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String today = sdf.format(d);
//上传后输出上传成功的时间
return today + "-" + fileName + "-" + "上传成功";
}catch (IllegalStateException e) {
return "文件过大,内存溢出异常";
}catch (IOException e) {
return "文件路径错误,IO异常";
}
}
添加回答
举报