MultipartFile问题
public Result save(@RequestParam(“file”) MultipartFile file,
@Valid CommonResource commonResource,
BindingResult bindingResult) {
//若不符合约束
if (bindingResult.hasErrors()){
//获取不符合约束时,自定义的异常信息
return Result.error(RetConstant.MISSING_PARAMETER,bindingResult.getFieldError().getDefaultMessage());
}
if(file.isEmpty()) {
return Result.error(“请选择文件”);
}
//查询标题是否已存在
CommonResource resource = commonResourceService.queryByTitleOrId(commonResource.getTitle(),null);
if (CommonUtils.isNotNull(resource)){
return Result.error(“标题已存在”);
}
return commonResourceService.save(file,commonResource,getUser().getJobNumber());
}
按照以上写法,前端必须传file参数过来,如果是修改的时候很不灵活,现改造如下:使用HttpServletRequest接收判断
@PostMapping(value = "/update")
public Result update(HttpServletRequest request,
@Valid CommonResource commonResource,
BindingResult bindingResult) {
MultipartFile picFile = null;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart){
MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request,
MultipartHttpServletRequest.class);
picFile = multipartRequest.getFile("file");
}
//若不符合约束
if (bindingResult.hasErrors()){
//获取不符合约束时,自定义的异常信息
return Result.error(RetConstant.MISSING_PARAMETER,
bindingResult.getFieldError().getDefaultMessage());
}
Long commonResourceID = commonResource.getCommonResourceID();
if (CommonUtils.isNull(commonResource)){
return Result.error(RetConstant.MISSING_PARAMETER,"更新ID不能为空");
} else {
//查看数据是否存在
CommonResource resource = commonResourceService.queryByTitleOrId(null,commonResourceID);
if (CommonUtils.isNull(resource)){
return Result.error("记录不存在");
} else {
String title = commonResource.getTitle();
if (!resource.getTitle().equals(title)){
//查标题是否重复
CommonResource resource1 = commonResourceService.queryByTitleOrId(
commonResource.getTitle(),null);
if (CommonUtils.isNotNull(resource1)){
return Result.error("标题已存在");
}
}
commonResource.setResourcePath(resource.getResourcePath());
return commonResourceService.update(picFile,commonResource);
}
}
}