图片上传
一、控制层
@ApiOperation(value = "图片上传", notes = "")
@PostMapping("/upload")
@Log(action = "文件上传")
public ResponseInfo save(MultipartFile file) {
Picture picture=pictureService.upload(file);
return ResponseInfo.success(picture);
}
二、service层
Picture upload(MultipartFile file);
三、serviceImpl层
public Picture upload(MultipartFile file) {
String fileName = file.getOriginalFilename().toString();
if (!StringUtils.isNotBlank(fileName)) {
throw new ErrorCodeException("图片上传不能为空");
}
//判断上传的图片结尾格式
Picture picture = new Picture();
//UUID
picture.setPicCode(UUID.randomUUID().toString().replace("-", ""));
//获取图片的后缀信息
int imgType = file.getOriginalFilename().lastIndexOf(".");
String imgTypeStr = file.getOriginalFilename().substring(imgType);
if (!imgTypeStr.equalsIgnoreCase(".jpg")
&& !imgTypeStr.equalsIgnoreCase(".jpeg")
&& !imgTypeStr.equalsIgnoreCase(".png")) {
throw new ErrorCodeException("上传的图片格式不正确");
}
//重新定义图片名称
String realPath = urlFile + "/webapps/picture" + "/" + UUID.randomUUID().toString().replace("-", "") + fileName.substring(fileName.lastIndexOf("."));
picture.setPicUrl(realPath);
picture.setPicType(1);
File dest = new File(realPath);
// 判断文件父目录是否存在
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest);
//保存图片信息
picture.setCreateTime(String.valueOf(System.currentTimeMillis()));
int i = pictureMapper.save(picture);
if (0 == i) {
throw new ErrorCodeException("保存图片信息失败");
}
} catch (IOException e) {
LOGGER.error("上传图片失败:", e);
}
return picture;
}