当前位置: 移动技术网 > IT编程>开发语言>Java > SpringBoot项目实现文件上传和邮件发送

SpringBoot项目实现文件上传和邮件发送

2019年05月30日  | 移动技术网IT编程  | 我要评论

米露恩的召唤有什么用,五四青年节祝福,王宝和澳门赌场不让进

前言

本篇文章主要介绍的是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.maxfilesizespring.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://www.lhsxpumps.com/_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方式进行请求

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网