经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
SpringBoot项目实现文件上传和邮件发送
来源:cnblogs  作者:虚无境  时间:2019/5/30 9:07:02  对本文有异议

前言

本篇文章主要介绍的是SpringBoot项目实现文件上传和邮件发送的功能。

SpringBoot 文件上传

说明:如果想直接获取工程那么可以直接跳到底部,通过链接下载工程代码。

开发准备

环境要求

JDK:1.8

SpringBoot:1.5.9.RELEASE

首先还是Maven的相关依赖:

pom.xml文件如下:

  1. <properties>
  2. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  3. <java.version>1.8</java.version>
  4. <maven.compiler.source>1.8</maven.compiler.source>
  5. <maven.compiler.target>1.8</maven.compiler.target>
  6. </properties>
  7. <parent>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-parent</artifactId>
  10. <version>1.5.9.RELEASE</version>
  11. <relativePath />
  12. </parent>
  13. <dependencies>
  14. <!-- Spring Boot Web 依赖 核心 -->
  15. <dependency>
  16. <groupId>org.springframework.boot</groupId>
  17. <artifactId>spring-boot-starter-web</artifactId>
  18. </dependency>
  19. <!-- Spring Boot Test 依赖 -->
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-test</artifactId>
  23. <scope>test</scope>
  24. </dependency>
  25. <!-- Spring Boot thymeleaf 模板 -->
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  29. </dependency>
  30. </dependencies>

然后就是application.properties的文件配置。

application.properties:

  1. banner.charset=UTF-8
  2. server.tomcat.uri-encoding=UTF-8
  3. spring.http.encoding.charset=UTF-8
  4. spring.http.encoding.enabled=true
  5. spring.http.encoding.force=true
  6. spring.messages.encoding=UTF-8
  7. server.port=8182
  8. spring.http.multipart.maxFileSize=100Mb
  9. spring.http.multipart.maxRequestSize=100Mb
  10. filePath=F:/test/

:其中spring.http.multipart.maxFileSizespring.http.multipart.maxRequestSize是设置上传文件的大小,这里我设置的是100Mb,filePath是文件上传的路径,因为个人使用的是Windows系统,所以将路径设置在F:/test/

代码编写

SpringBoot自身对于文件上传可以说是非常的友好了,只需要在控制层的参数中使用MultipartFile这个类,然后接受file类型的数据上传就可以了,至于将上传得到的文件如何处理就是我们开发者自己决定了。

首先我们先写一个前端界面,在界面上新增一个按钮用于上传文件。由于SpringBoot对thymeleaf的支持非常友好,所以这里我们就直接使用thymeleaf编写一个简单的界面,用于上传文件。

html代码如下:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>uploading.html</title>
  5. <meta name="keywords" content="keyword1,keyword2,keyword3"></meta>
  6. <meta name="description" content="this is my page"></meta>
  7. <meta name="content-type" content="text/html; charset=UTF-8"></meta>
  8. </head>
  9. <body>
  10. <form enctype="multipart/form-data" method="post" action="/uploading">
  11. <input type="file" name="file"/>
  12. <input type="submit" value="上传"/>
  13. </form>
  14. </body>
  15. </html>

注: 如果不想编写前端界面的话,也可以通过Postman等工具实现。
Postman的操作方式为:

填写url路径,选择post方式 -> body 选择form-data 格式-> key选择file类型,选择文件,然后点击send就可以实现文件上传。

因为我们这里只进行文件上传,并不做其它的业务逻辑处理,因此我们只用在控制层实现即可。定义一个文件上传的接口,然后使用MultipartFile类进行接收即可。

代码如下:

  1. @Controller
  2. public class FileUploadController {
  3. @Value("${filePath}")
  4. private String filePath;
  5. @GetMapping("/upload")
  6. public String uploading() {
  7. //跳转到 templates 目录下的 uploading.html
  8. return "uploading";
  9. }
  10. //处理文件上传
  11. @PostMapping("/uploading")
  12. public @ResponseBody String uploading(@RequestParam("file") MultipartFile file,
  13. HttpServletRequest request) {
  14. try {
  15. uploadFile(file.getBytes(), filePath, file.getOriginalFilename());
  16. } catch (Exception e) {
  17. e.printStackTrace();
  18. System.out.println("文件上传失败!");
  19. return "uploading failure";
  20. }
  21. System.out.println("文件上传成功!");
  22. return "uploading success";
  23. }
  24. public void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
  25. File targetFile = new File(filePath);
  26. if(!targetFile.exists()){
  27. targetFile.mkdirs();
  28. }
  29. FileOutputStream out = new FileOutputStream(filePath+fileName);
  30. out.write(file);
  31. out.flush();
  32. out.close();
  33. }
  34. }

:上述的代码只是一个示例,实际的情况下请注意异常的处理!上述的流关闭理应放在finally中,实际为了方便才如此的编写。

App 入口

和普通的SpringBoot项目基本一样。

代码如下:

  1. @SpringBootApplication
  2. public class FileUploadApplication {
  3. public static void main(String[] args) {
  4. SpringApplication.run(FileUploadApplication.class, args);
  5. System.out.println("FileUploadApplication 程序启动成功!");
  6. }
  7. }

功能测试

我们成功启动该程序之后,在浏览器上输入:http://localhost:8182/upload,然后选择一个文件进行上传,最后我们再到F:/test/路径下查看是否有该文件。

示例图如下:

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

使用Postman上传的示例图:

在这里插入图片描述

最后说明一下,如果文件重复上传,后面上传的文件会替换掉之前的那个文件。

SpringBoot 邮件发送

说明:如果想直接获取工程那么可以直接跳到底部,通过链接下载工程代码。

开发准备

环境要求

JDK:1.8

SpringBoot:1.5.9.RELEASE

首先还是Maven的相关依赖:

pom.xml文件如下:

  1. <properties>
  2. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  3. <java.version>1.8</java.version>
  4. <maven.compiler.source>1.8</maven.compiler.source>
  5. <maven.compiler.target>1.8</maven.compiler.target>
  6. </properties>
  7. <parent>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-parent</artifactId>
  10. <version>1.5.9.RELEASE</version>
  11. <relativePath />
  12. </parent>
  13. <dependencies>
  14. <!-- Spring Boot Web 依赖 核心 -->
  15. <dependency>
  16. <groupId>org.springframework.boot</groupId>
  17. <artifactId>spring-boot-starter-web</artifactId>
  18. </dependency>
  19. <!-- Spring Boot Test 依赖 -->
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-test</artifactId>
  23. <scope>test</scope>
  24. </dependency>
  25. <!-- Spring Boot thymeleaf 模板 -->
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-starter-mail</artifactId>
  33. </dependency>
  34. <dependency>
  35. <groupId>org.springframework</groupId>
  36. <artifactId>spring-context-support</artifactId>
  37. </dependency>
  38. </dependencies>

然后就是application.properties的文件配置,这里我们需要根据自己的实际情况进行填写。如下述的配置文件示例中,个人使用的是qq邮箱,因此spring.mail.host配置的是smtp.qq.com。下述的示例中,只需填写个人邮箱的账号和密码即可。如果出现了535 错误,则需要该邮箱开启POP3/SMTP服务,并且使用授权码替换密码进行发送。

application.properties:

  1. server.port = 8182
  2. spring.mail.host=smtp.qq.com
  3. spring.mail.username=xxx@qq.com
  4. spring.mail.password=xxx
  5. spring.mail.default-encoding=UTF-8
  6. spring.mail.properties.mail.smtp.auth=true
  7. spring.mail.properties.mail.smtp.starttls.enable=true
  8. spring.mail.properties.mail.smtp.starttls.required=true

代码编写

SpringBoot这块已经集成了mail邮件发送的功能,我们引入相关架包之后,只需使用JavaMailSender这个类中的send方法即可完成邮件的发送。如果还想发送静态资源和附件的邮件,在JavaMailSender这个类中的方法也可以实现。如果想使用自定义的模板内容发送的话,则需要使用TemplateEngine 该类中的方法。

在我们使用邮件发送的时候,这四样最为重要,发件人、收件人、发送主题和发送的消息。因此我们可以根据这四样来创建一个简答的邮件实体类,方便进行相关的业务处理。

实体类代码

代码如下:

  1. public class Mail {
  2. /** 发送者*/
  3. private String sender;
  4. /** 接受者 */
  5. private String receiver;
  6. /** 主题 */
  7. private String subject;
  8. /** 发送 消息*/
  9. private String text;
  10. //getter 和 setter 略
  11. }

这里我们还是定义接口来进行邮件的发送,我们发送邮件的时候依旧只需要知道发件人、收件人、发送主题和发送的消息这四点就可以了,其余的可以在代码中完成。这里我们就简单的定义几个接口,用于实现上述的要求

控制层代码:

代码如下:

  1. @RestController
  2. @RequestMapping("/api/mail")
  3. public class MailController {
  4. private static Logger LOG=LoggerFactory.getLogger(MailController.class);
  5. @Autowired
  6. private JavaMailSender mailSender;
  7. @Autowired
  8. private TemplateEngine templateEngine;
  9. /*
  10. * 发送普通邮件
  11. */
  12. @PostMapping("/sendMail")
  13. public String sendMail(@RequestBody Mail mail) {
  14. SimpleMailMessage message = new SimpleMailMessage();
  15. message.setFrom(mail.getSender());
  16. message.setTo(mail.getReceiver());
  17. message.setSubject(mail.getSubject());
  18. message.setText(mail.getText());
  19. mailSender.send(message);
  20. LOG.info("发送成功!");
  21. return "发送成功!";
  22. }
  23. /*
  24. * 发送附件
  25. */
  26. @PostMapping("/sendAttachments")
  27. public String sendAttachmentsMail(@RequestBody Mail mail) throws MessagingException {
  28. MimeMessage mimeMessage = mailSender.createMimeMessage();
  29. MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
  30. helper.setFrom(mail.getSender());
  31. helper.setTo(mail.getReceiver());
  32. helper.setSubject(mail.getSubject());
  33. helper.setText(mail.getText());
  34. FileSystemResource file = new FileSystemResource(new File("1.png"));
  35. helper.addAttachment("附件.jpg", file);
  36. mailSender.send(mimeMessage);
  37. return "发送成功!";
  38. }
  39. /*
  40. * 发送文件
  41. */
  42. @PostMapping("/sendInlineMail")
  43. public String sendInlineMail(@RequestBody Mail mail) throws Exception {
  44. MimeMessage mimeMessage = mailSender.createMimeMessage();
  45. MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
  46. helper.setFrom(mail.getSender());
  47. helper.setTo(mail.getReceiver());
  48. helper.setSubject(mail.getSubject());
  49. //这里的text 是html
  50. helper.setText(mail.getText(), true);
  51. FileSystemResource file = new FileSystemResource(new File("1.png"));
  52. helper.addInline("文件", file);
  53. mailSender.send(mimeMessage);
  54. return "发送成功!";
  55. }
  56. /*
  57. * 发送模板
  58. */
  59. @PostMapping("/sendTemplateMail")
  60. public void sendTemplateMail(@RequestBody Mail mail) throws Exception {
  61. MimeMessage mimeMessage = mailSender.createMimeMessage();
  62. MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
  63. helper.setFrom(mail.getSender());
  64. helper.setTo(mail.getReceiver());
  65. helper.setSubject(mail.getSubject());
  66. //创建邮件正文
  67. Context context = new Context();
  68. context.setVariable("id", "1");
  69. context.setVariable("name", "xuwujing");
  70. String emailContent = templateEngine.process("emailTemplate", context);
  71. helper.setText(emailContent, true);
  72. mailSender.send(mimeMessage);
  73. }
  74. }

App 入口

和普通的SpringBoot项目基本一样。

代码如下:

  1. @SpringBootApplication
  2. public class MailApp
  3. {
  4. public static void main( String[] args )
  5. {
  6. SpringApplication.run(MailApp.class, args);
  7. System.out.println("MailApp启动成功!");
  8. }
  9. }

功能测试

我们成功启动该程序之后,我们使用Postman工具进行测试。

使用POST方式进行请求

POST http://localhost:8182/api/mail/sendMail

Body参数为:

{
"sender":"xxx@qq.com",
"receiver":"xxx@qq.com",
"subject":"测试主题",
"text":"测试消息"
}

:当然这里的参数填写你自己的邮箱即可!

返回参数为:

发送成功!

示例图:
在这里插入图片描述
可以看到邮件已经发送成功了!

有的同学可能不知道授权码如何生成,这里我就用QQ邮箱生成授权码的一张示例图来说明。

示例图:
在这里插入图片描述

其它

关于SpringBoot项目实现文件上传和邮件发送的功能的文章就讲解到这里了,如有不妥,欢迎指正!

项目地址

SpringBoot实现文件上传的项目工程地址:
https://github.com/xuwujing/springBoot-study/tree/master/springboot-fileUpload

SpringBoot实现邮件发送的项目工程地址:
https://github.com/xuwujing/springBoot-study/tree/master/springboot-mail

SpringBoot整个集合的地址:
https://github.com/xuwujing/springBoot-study

SpringBoot整合系列的文章

音乐推荐

推荐一首在静下心来看书的纯音乐!

原创不易,如果感觉不错,希望给个推荐!您的支持是我写作的最大动力!
版权声明:
作者:虚无境
博客园出处:http://www.cnblogs.com/xuwujing
CSDN出处:http://blog.csdn.net/qazwsxpcm    
个人博客出处:http://www.panchengming.com

原文链接:http://www.cnblogs.com/xuwujing/p/10945698.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号