springBoot 文件上传和邮件发送

该文章详细介绍了如何在SpringBoot应用中实现文件上传,通过接收前端传递的文件,存储到服务器,并返回文件的URL。同时,文章还展示了如何发送带有附件的邮件,包括设置邮件主题、正文和收件人,以及处理邮件附件的功能。
摘要由CSDN通过智能技术生成

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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值