1、controller层代码:
/**
* 手动发表评论
*
* @param commentInfoVO 评论信息VO对象
* @return 处理结果
*/
@PatchMapping("/")
public Boolean publishComment(HttpServletRequest request, CommentInfoVO commentInfoVO, MultipartFile[] files) {
try {
// 为评论设置是否晒图
Integer showPictures = ShowPictures.NO;
if (files != null && files.length > 0) {
for (MultipartFile file : files) {
if (file != null) {
showPictures = ShowPictures.YES;
break;
}
}
}
commentInfoVO.setShowPictures(showPictures);
//保存评论信息
CommentInfoDTO commentInfoDTO = commentInfoVO.clone(CommentInfoDTO.class);
commentInfoService.saveManualPublishedCommentInfo(commentInfoDTO);
// 上传评论晒图图片
String appBasePath = request.getSession().getServletContext().getRealPath("/");
commentPictureService.saveCommentPictures(appBasePath, commentInfoDTO.getId(), files);
// 更新评论统计信息
commentAggregateService.refreshCommentAggregate(commentInfoDTO);
// 通知订单中心订单已经发表了评论
orderFacadeService.informPublishCommentEvent(commentInfoDTO.getOrderInfoId());
// 通知会员中心用户已经发表了评论
membershipFacadeService.informPublishCommentEvent(
commentInfoDTO.getUserAccountId(), ShowPictures.YES.equals(showPictures));
} catch (Exception e) {
logger.error("发表评论失败", e);
return false;
}
return true;
}
2、service层代码实现
/**
* 保存评论晒图
*
* @param appBasePath 当前应用的根路径
* @param commentInfoId 评论信息id
* @param files 评论晒图
* @return 处理结果
*/
@Override
public Boolean saveCommentPictures(String appBasePath, Long commentInfoId, MultipartFile[] files) {
//处理上传路径
if (CommentPictureUploadDirType.RELATIVE.equals(uploadDirType)) {
uploadDirPath = appBasePath + uploadDirPath;
}
//将图片上传到指定目录去
try {
// 如果上传目录不存在,则自动创建该目录
File uploadDir = new File(uploadDirPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
for (MultipartFile file : files) {
if (file == null) {
continue;
}
// 如果目标文件路径已经存在,则删除目标文件
String targetFilePath = uploadDirPath + file.getOriginalFilename();
File targetFile = new File(targetFilePath);
if (targetFile.exists()) {
targetFile.delete();
}
// 将上传上来的文件保存到指定的文件中去
file.transferTo(targetFile);
String format = dateTimeFormatter.format(LocalDateTime.now());
// 将评论晒图信息保存到数据库中去
CommentPictureDO commentPictureDO = new CommentPictureDO();
commentPictureDO.setCommentPicturePath(targetFilePath);
commentPictureDO.setCommentInfoId(commentInfoId);
commentPictureDO.setGmtCreate(format);
commentPictureDO.setGmtModified(format);
commentPictureDAO.saveCommentPicture(commentPictureDO);
}
} catch (Exception e) {
logger.error("保存图片失败", e);
return false;
}
return true;
}
3、配置文件
comment.picture.upload.dir.type=relative
comment.picture.upload.dir=/upload/
网友评论