前言
本篇文章主要介紹的是SpringBoot項目實現文件上傳和郵件發送的功能。
SpringBoot 文件上傳
說明:如果想直接獲取工程那么可以直接跳到底部,通過鏈接下載工程代碼。
開發准備
環境要求
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>
</dependencies>
然后就是application.properties的文件配置。
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/
。
代碼編寫
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上傳的示例圖:
最后說明一下,如果文件重復上傳,后面上傳的文件會替換掉之前的那個文件。
SpringBoot 郵件發送
說明:如果想直接獲取工程那么可以直接跳到底部,通過鏈接下載工程代碼。
開發准備
環境要求
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方式進行請求
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