【SpringBoot】DEMO:上传头像并把头像的路径存放到数据库

【SpringBoot】DEMO:上传头像并把头像的路径存放到数据库

一、任务介绍

  1. 判断图片是否为空,不为空,把图片上传到服务器
  2. 把图片的路径写入数据库

二、目录结构

在这里插入图片描述

三、功能实现

  1. maven依赖如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-core</artifactId>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!--整合mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--json @responseBody/@requestBody-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.54</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

  1. 建立两个HTML页面,index是上传图片,success为上传成功后的跳转页面
  • index页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>上传图片展示区</title>
</head>
<body>
选择图片:
<form enctype="multipart/form-data" method="post" action="/doUpload">
    <input type="file" name="file"/>
    <input type="submit" value="上传">
</form>
<span th:text="${error}"></span>
</body>
</html>
  • success页面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传成功</title>
</head>
<body>
上传成功
</body>
</html>
  1. 控制器Controller
  • 一个是用于控制跳转页面
//跳转到上传文件的页面
    @RequestMapping(value = "/" , method = RequestMethod.GET)
    public String goUploadImg(){
        return "index";
    }

  • 一个用于存放图片并写入把路径写入数据库
    //处理上传的文件
    @PostMapping("/doUpload")
    public String uploadImg(
            // 定义一个 MultipartFile 类型的参数 file
            @RequestParam("file") MultipartFile file,
            Model model){
        // 如果图片为空,显示error
        if ((file.getOriginalFilename().isEmpty() )) {
            model.addAttribute("error","error");
            return "index";
        }else{
            Head head = new Head();
            // 获取图片的名字
            String fileName = file.getOriginalFilename();
            // 图片存放的文件夹地址
            String filePath = "C:\\Users\\Lzy\\Desktop\\head\\";
            // 文件夹地址 + 名字 = 图片的路径
            String fileAddress = filePath + fileName;
            try{
                // 图片上传的工具类
                // 参数一:图片的编码格式的字节数组
                // 参数二:图片存放的文件夹地址
                // 参数三:图片的名字
                FileUtil.uploadFile(file.getBytes(),filePath,fileName);
                
                // 把图片路径写入数据库
                head.setHeadAddress(fileAddress);
                addHeadAddress.insert(head);
                
            } catch (Exception e){
            }
            return "success";
        }
    }
  1. JavaBean,跟数据库一一对应
  • 只存放id和图片路径
package com.example.demo.Model;

public class Head {

    public String headAddress;
    public Integer id;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getHeadAddress() {
        return headAddress;
    }

    public void setHeadAddress(String headAddress) {
        this.headAddress = headAddress;
    }
}

  1. Mapping,存放与数据库有关的操作
  • 这里只有插入方法
@Mapper@Repository
public interface AddHeadAddress {
    @Insert("insert into head(headAddress) values (#{headAddress})")
    void insert(Head head);
}
  1. 图片上传的工具类
public class FileUtil {

    //上传文件的工具类
    public static 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();
    }
}

四、实现效果

C:\\Users\\Lzy\\Desktop\\head\\

这是我存放图片的路径(桌面的head文件夹),在Controller中有写

在这里插入图片描述

五、大功告成!

发布了28 篇原创文章 · 获赞 4 · 访问量 1313

猜你喜欢

转载自blog.csdn.net/weixin_44100826/article/details/104522375
今日推荐