百木园-与人分享,
就是让自己快乐。

SpringBoot 增删改查+文件上传

注:本文所用到的版本

MySql 8.0.28
SpringBoot 2.7.2

准备工作 :建表 、pom.xml导入依赖 、application.yml 配置

  • 建表
CREATE TABLE `rna` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `card_img` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `card` varchar(18) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `sex` varchar(2) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `phone` varchar(11) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `check` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `check_date` datetime DEFAULT NULL,
  `result` varchar(2) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

  • pom.xml导入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 生成get  set -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<!-- msql数据库 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- druid数据源 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.11</version>
</dependency>
<!-- mybatis启动器 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>
<!-- pageHelper分页插件 -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.4.2</version>
</dependency>
<!-- 文件上传 -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>
  • application.yml 配置
server:
  port: 8100
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/db03
    username: 你的用户名
    password: 你的密码
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
mybatis:
  mapper-locations: mapper/*.xml
  type-aliases-package: com.lyt.pojo

目录结构

上传文件工具类

package com.lyt.util;

import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author liuyutao
 * @date 2022/07/27
 */
public class UploadUtil {

    //上传文件的路径前缀
    public static String uploadPathPrefix = \"D:\\\\upload\\\\images\\\\\";

    public static String upload(MultipartFile uploadFile, String oldPath) {
        String uploadFullPath;//上传文件的完整路径
        String saveSqlPartFilePath;//返回该属性,保存到数据库部分文件路径
        if (ObjectUtils.isEmpty(oldPath)) {
            String originalFilename = uploadFile.getOriginalFilename();//上传文件原始文件名
            assert originalFilename != null;
            String fileType = originalFilename.substring(originalFilename.lastIndexOf(\".\"));//文件类型
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy\\\\M\\\\\");
            String format = sdf.format(date);
            String uuid = UUID.randomUUID().toString().replace(\"-\", \"\");
            String saveDiskFileName = uuid + fileType;// 保存到磁盘的文件名
            saveSqlPartFilePath = format + saveDiskFileName;
            uploadFullPath = uploadPathPrefix + saveSqlPartFilePath;//上传文件的完整路径:  D:\\\\upload\\\\images\\\\ yyyy\\\\M\\\\uuid文件名
        } else {
            uploadFullPath = uploadPathPrefix + oldPath;
            saveSqlPartFilePath = oldPath;
        }
        File file = new File(uploadFullPath);
        try {
            if (!file.exists()) {
                file.mkdirs();
            }
            uploadFile.transferTo(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return saveSqlPartFilePath;
    }
}

SpringBoot 虚拟路径映射

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {   		registry.addResourceHandler(\"/upload/**\").addResourceLocations(\"file:D:/upload/images/\");
    }

}

新增 + 上传文件

@PostMapping(\"/addRna\")
public int addRna(@RequestParam(\"file\") MultipartFile file, @RequestPart Rna rna) {
    String cardImg = UploadUtil.upload(file, null);
    rna.setCardImg(cardImg);
    return rnaService.insertSelective(rna);
}

思路:

  • 文件 和 对象数据 同时访问一个接口
  • 上传文件后返回文件的部分路径,非全路径
  • 设置到rna对象,一同添加到数据库

编辑 + 上传文件

 @PostMapping(\"/updateRna\")
 public int updateRna(@RequestParam(\"file\") MultipartFile file, @RequestPart Rna rna) {
     if (!file.isEmpty()) {
     Rna rnaById = rnaService.selectByPrimaryKey(rna.getId());
     UploadUtil.upload(file, rnaById.getCardImg());
     }
     return rnaService.updateByPrimaryKeySelective(rna);
 }
  • 这里不是删除原来文件,而是同路径同文件名,覆盖原文件

  • 有上传新文件,则覆盖原文件,编辑其他字段数据

  • 没有上传文件,编辑其他字段数据

查询

  • PageHelper 插件分页
  • 拼接文件的完整url访问路径

删除

  • 删除数据库数据 + 删除文件

来源:https://www.cnblogs.com/liuyutao0206/p/16529395.html
本站部分图文来源于网络,如有侵权请联系删除。

未经允许不得转载:百木园 » SpringBoot 增删改查+文件上传

相关推荐

  • 暂无文章