SpringBoot 文件上传
问题背景: 前端点击发送一个附件,传递给后端,后端将文件存储到服务器中。
Spring代码
springController (仅参考,根据实际需求编写)
@PostMapping(value = "/files/upload", headers = "Content-Type=multipart/form-data")
@ResponseBody
@ApiImplicitParams(
@ApiImplicitParam(name = "files", value = "文件", dataType = "body", paramType = "body", allowMultiple = true, required = true)
)
public Response<List<ContactAuditUploadVo>> filesUpload(@RequestBody @ApiParam(value = "files", required = true) MultipartFile[] files) {
Response response = new Response();
try {
response.setBody(contactAuditService.filesUpload(files));
} catch (Exception e) {
log.error(e.getMessage());
response.setReturnCode(ResponseCode.COMMON_ERROR.getReturnCode());
response.setReturnMsg(e.getMessage());
return response;
}
return response;
}
service层
service层接口
public ContactAuditUploadVo fileUpload(MultipartFile file) {
ContactAuditUploadVo contactAuditUploadVo = new ContactAuditUploadVo();
if (null != file) {
AttachVo attachVo = FilesUtils.fileUpload1(file, baseEmailDir, DateUtils.getNowDateString());
if (attachVo.getAttachUrl() != null) {
contactAuditUploadVo.setAttachUrl(attachVo.getAttachUrl());
}
if (attachVo.getAttachName() != null) {
contactAuditUploadVo.setAttachName(attachVo.getAttachName());
}
}
return contactAuditUploadVo;
}
文件上传的核心代码
/**
* 文件上传修改
*
* @param file
* @param sysDate
* @return
*/
public static AttachVo fileUpload1(MultipartFile file, String baseDir, String sysDate) {
AttachVo attachVo = new AttachVo();
String path = "";
if (!file.isEmpty()) {
try {
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取uuid
String uuid = UUID.randomUUID().toString().replace("-", "");
// 文件路径
path = uuid + fileName;
File filePath = new File(baseDir, path);
// 如果存放路径的父路径不存在,就创建它
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();
}
log.info("文件保存路径:{},是否存在:{}", filePath.getParentFile().exists(), filePath.getParent());
file.transferTo(filePath.getAbsoluteFile()); // 注意这里的路径!!!
log.info("文件成功保存的路径:{}", filePath.getAbsolutePath());
log.info("文件上传成功....");
attachVo.setAttachName(fileName);
attachVo.setAttachUrl(filePath.getAbsolutePath());
} catch (IOException e) {
log.error("文件上传失败....", e);
e.printStackTrace();
}
}
return attachVo;
}
对应返回的实体类
attachVo实体类
// 返回对应的文件名称和url地址
@Data
public class AttachVo {
private String attachUrl;
private String attachName;
}
注:如果传入的是空文件,里面没有任何内容,文件将不会保存到服务器中,因为代码中作了判空处理.
SpringBoot 邮件发送
需求背景: 前端传递对于的附件(可带附件也可不带附件),主题,内容,收件人邮箱即可。
Controller层
@ApiOperation(value = "邮件发送")
@PostMapping("/emailSend")
private Response emailSend(@RequestBody EmailSendRequest request) {
Response<Object> response = new Response<>();
try {
emailTemplateService.sendEmail(request);
} catch (Exception e) {
log.error(e.getMessage());
response.setReturnCode(ResponseCode.COMMON_ERROR.getReturnCode());
response.setReturnMsg(e.getMessage());
return response;
}
return response;
}
Service层
@Override
public void sendEmail(EmailSendRequest request) {
String receiver = request.getReceiver();
String content = request.getContent();
String theme = request.getTheme();
List<String> attachUrl = request.getAttachUrl();
sendAttachmentsMail(receiver, theme, content, attachUrl);
}
发送邮件的核心方法
发送邮件的核心代码 ,可以替换直接使用
/**
* 发送带附件的邮件
*
* @param to
* @param subject
* @param content
* @param filePath
*/
public void sendAttachmentsMail(String to, String subject, String content,
List<String> filePath) {
log.info("sendStaticMailStart...{},{},{},{}", to, subject, content, filePath);
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = null;
try {
helper = new MimeMessageHelper(message, true);
// 收件人和发送人
helper.setTo(to);
helper.setFrom(from);
// 发送主题
helper.setSubject(subject);
// 发送正文
helper.setText(content, true);
if (!CollectionUtils.isEmpty(filePath)) {
for (String path : filePath) {
FileSystemResource file = new FileSystemResource(new File(path));
// 返回文件附件
String fileName = file.getFilename();
if (fileName != null) {
// 使用MimeUtily.excodeText对附件名称进行编码,解决附件名称为中文问题
// 这里的fileName可以自己定义,保证后缀名称一致即可
helper.addAttachment(MimeUtilty.encodeText(fileName), file);
}
}
}
javaMailSender.send(message);
log.info("sendEmailSuccessful....");
} catch (MessagingException e) {
log.error("sendEmailFail....", e);
}
}
// 中文字段过长回截取,用下面的配置在中文过长时不会截取,在发送的时候初始化splitLongParameters为false不截取:
static {
System.setProperty("mail.mime.splitlongparameters","false");
}
在这里插入代码片
注:这里需要注入 javaMailSender
@Autowired
private JavaMailSender javaMailSender;
添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.5.3</version>
</dependency>
注意: yml中一定要添加发送邮件人的信息,否则运行会报错
yml中配置对应的地址
spring:
mail:
host: smtp.163.com // 这里对于的是163邮箱
password: URGUJVHWUNJPYCE // 授权码
username: qianjs0206@163.com // 用户邮箱名称
port: // 端口号默认为25