本篇文章主要介紹的是SpringBoot項目實現文件上傳和郵件發送的功能。html
說明:若是想直接獲取工程那麼能夠直接跳到底部,經過連接下載工程代碼。前端
環境要求java
JDK:1.8git
SpringBoot:1.5.9.RELEASEgithub
首先仍是Maven的相關依賴:web
pom.xml文件以下:spring
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath /> </parent> <dependencies> <!-- Spring Boot Web 依賴 核心 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Boot Test 依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- Spring Boot thymeleaf 模板 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies>
而後就是application.properties的文件配置。api
application.properties:瀏覽器
banner.charset=UTF-8 server.tomcat.uri-encoding=UTF-8 spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true spring.http.encoding.force=true spring.messages.encoding=UTF-8 server.port=8182 spring.http.multipart.maxFileSize=100Mb spring.http.multipart.maxRequestSize=100Mb filePath=F:/test/
注:其中spring.http.multipart.maxFileSize
和spring.http.multipart.maxRequestSize
是設置上傳文件的大小,這裏我設置的是100Mb,filePath
是文件上傳的路徑,由於我的使用的是Windows系統,因此將路徑設置在F:/test/
。tomcat
SpringBoot自身對於文件上傳能夠說是很是的友好了,只須要在控制層的參數中使用MultipartFile
這個類,而後接受file
類型的數據上傳就能夠了,至於將上傳獲得的文件如何處理就是咱們開發者本身決定了。
首先咱們先寫一個前端界面,在界面上新增一個按鈕用於上傳文件。因爲SpringBoot對thymeleaf的支持很是友好,因此這裏咱們就直接使用thymeleaf編寫一個簡單的界面,用於上傳文件。
html代碼以下:
<!DOCTYPE html> <html> <head> <title>uploading.html</title> <meta name="keywords" content="keyword1,keyword2,keyword3"></meta> <meta name="description" content="this is my page"></meta> <meta name="content-type" content="text/html; charset=UTF-8"></meta> </head> <body> <form enctype="multipart/form-data" method="post" action="/uploading"> <input type="file" name="file"/> <input type="submit" value="上傳"/> </form> </body> </html>
注: 若是不想編寫前端界面的話,也能夠經過Postman等工具實現。
Postman的操做方式爲:
填寫url路徑,選擇post方式 -> body 選擇form-data 格式-> key選擇file類型,選擇文件,而後點擊send就能夠實現文件上傳。
由於咱們這裏只進行文件上傳,並不作其它的業務邏輯處理,所以咱們只用在控制層實現便可。定義一個文件上傳的接口,而後使用MultipartFile
類進行接收便可。
代碼以下:
@Controller public class FileUploadController { @Value("${filePath}") private String filePath; @GetMapping("/upload") public String uploading() { //跳轉到 templates 目錄下的 uploading.html return "uploading"; } //處理文件上傳 @PostMapping("/uploading") public @ResponseBody String uploading(@RequestParam("file") MultipartFile file, HttpServletRequest request) { try { uploadFile(file.getBytes(), filePath, file.getOriginalFilename()); } catch (Exception e) { e.printStackTrace(); System.out.println("文件上傳失敗!"); return "uploading failure"; } System.out.println("文件上傳成功!"); return "uploading success"; } public void uploadFile(byte[] file, String filePath, String fileName) throws Exception { File targetFile = new File(filePath); if(!targetFile.exists()){ targetFile.mkdirs(); } FileOutputStream out = new FileOutputStream(filePath+fileName); out.write(file); out.flush(); out.close(); } }
注:上述的代碼只是一個示例,實際的狀況下請注意異常的處理!上述的流關閉理應放在finally中,實際爲了方便才如此的編寫。
App 入口
和普通的SpringBoot項目基本同樣。
代碼以下:
@SpringBootApplication public class FileUploadApplication { public static void main(String[] args) { SpringApplication.run(FileUploadApplication.class, args); System.out.println("FileUploadApplication 程序啓動成功!"); } }
咱們成功啓動該程序以後,在瀏覽器上輸入:http://localhost:8182/upload
,而後選擇一個文件進行上傳,最後咱們再到F:/test/
路徑下查看是否有該文件。
示例圖以下:
使用Postman上傳的示例圖:
最後說明一下,若是文件重複上傳,後面上傳的文件會替換掉以前的那個文件。
說明:若是想直接獲取工程那麼能夠直接跳到底部,經過連接下載工程代碼。
環境要求
JDK:1.8
SpringBoot:1.5.9.RELEASE
首先仍是Maven的相關依賴:
pom.xml文件以下:
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath /> </parent> <dependencies> <!-- Spring Boot Web 依賴 核心 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Boot Test 依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- Spring Boot thymeleaf 模板 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> </dependency> </dependencies>
而後就是application.properties的文件配置,這裏咱們須要根據本身的實際狀況進行填寫。以下述的配置文件示例中,我的使用的是qq郵箱,所以spring.mail.host
配置的是smtp.qq.com
。下述的示例中,只需填寫我的郵箱的帳號和密碼便可。若是出現了535 錯誤,則須要該郵箱開啓POP3/SMTP服務,而且使用受權碼替換密碼進行發送。
application.properties:
server.port = 8182 spring.mail.host=smtp.qq.com spring.mail.username=xxx@qq.com spring.mail.password=xxx spring.mail.default-encoding=UTF-8 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true
SpringBoot這塊已經集成了mail郵件發送的功能,咱們引入相關架包以後,只需使用JavaMailSender
這個類中的send方法便可完成郵件的發送。若是還想發送靜態資源和附件的郵件,在JavaMailSender
這個類中的方法也能夠實現。若是想使用自定義的模板內容發送的話,則須要使用TemplateEngine
該類中的方法。
在咱們使用郵件發送的時候,這四樣最爲重要,發件人、收件人、發送主題和發送的消息。所以咱們能夠根據這四樣來建立一個簡答的郵件實體類,方便進行相關的業務處理。
實體類代碼
代碼以下:
public class Mail { /** 發送者*/ private String sender; /** 接受者 */ private String receiver; /** 主題 */ private String subject; /** 發送 消息*/ private String text; //getter 和 setter 略 }
這裏咱們仍是定義接口來進行郵件的發送,咱們發送郵件的時候依舊只須要知道發件人、收件人、發送主題和發送的消息這四點就能夠了,其他的能夠在代碼中完成。這裏咱們就簡單的定義幾個接口,用於實現上述的要求
控制層代碼:
代碼以下:
@RestController @RequestMapping("/api/mail") public class MailController { private static Logger LOG=LoggerFactory.getLogger(MailController.class); @Autowired private JavaMailSender mailSender; @Autowired private TemplateEngine templateEngine; /* * 發送普通郵件 */ @PostMapping("/sendMail") public String sendMail(@RequestBody Mail mail) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(mail.getSender()); message.setTo(mail.getReceiver()); message.setSubject(mail.getSubject()); message.setText(mail.getText()); mailSender.send(message); LOG.info("發送成功!"); return "發送成功!"; } /* * 發送附件 */ @PostMapping("/sendAttachments") public String sendAttachmentsMail(@RequestBody Mail mail) throws MessagingException { MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setFrom(mail.getSender()); helper.setTo(mail.getReceiver()); helper.setSubject(mail.getSubject()); helper.setText(mail.getText()); FileSystemResource file = new FileSystemResource(new File("1.png")); helper.addAttachment("附件.jpg", file); mailSender.send(mimeMessage); return "發送成功!"; } /* * 發送文件 */ @PostMapping("/sendInlineMail") public String sendInlineMail(@RequestBody Mail mail) throws Exception { MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setFrom(mail.getSender()); helper.setTo(mail.getReceiver()); helper.setSubject(mail.getSubject()); //這裏的text 是html helper.setText(mail.getText(), true); FileSystemResource file = new FileSystemResource(new File("1.png")); helper.addInline("文件", file); mailSender.send(mimeMessage); return "發送成功!"; } /* * 發送模板 */ @PostMapping("/sendTemplateMail") public void sendTemplateMail(@RequestBody Mail mail) throws Exception { MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setFrom(mail.getSender()); helper.setTo(mail.getReceiver()); helper.setSubject(mail.getSubject()); //建立郵件正文 Context context = new Context(); context.setVariable("id", "1"); context.setVariable("name", "xuwujing"); String emailContent = templateEngine.process("emailTemplate", context); helper.setText(emailContent, true); mailSender.send(mimeMessage); } }
App 入口
和普通的SpringBoot項目基本同樣。
代碼以下:
@SpringBootApplication public class MailApp { public static void main( String[] args ) { SpringApplication.run(MailApp.class, args); System.out.println("MailApp啓動成功!"); } }
咱們成功啓動該程序以後,咱們使用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
推薦一首在靜下心來看書的純音樂!
原創不易,若是感受不錯,但願給個推薦!您的支持是我寫做的最大動力! 版權聲明: 做者:虛無境 博客園出處:http://www.cnblogs.com/xuwujing CSDN出處:http://blog.csdn.net/qazwsxpcm 我的博客出處:http://www.panchengming.com