Springboot2 uploads pictures to the server through MultipartFile, and saves the file path to the database

1. Environmental preparation

System: win11

Development environment: IDEA 2023.1.2 + Jdk8 + Springboot2.7.10

Database: mysql5.7

Two: Background

Implement a front-end uploading pictures to the background server to specify the path, and store the path in the database.

3. Code structure

pom.xml

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.12</version>
            <!--<scope>runtime</scope>-->
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>

<!-- Alibaba's druid database connection pool -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>20.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.2</version>
        </dependency>

        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

Springboot configures application.yml. The maximum file setting here is 1MB by default. You can modify the setting to be larger to avoid the error that the file size is limited.

server:
  port: 8888
web:
  upload-path: F:/zp/uploadImageDir
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true &characterEncoding=UTF-8 &useSSL=false &serverTimezone=Asia/Shanghai
    username: root
    password: 346498
    driver-class-name: com.mysql.jdbc.Driver
  servlet:
    multipart:
      enabled: true
      max-file-size: 10MB
      max-request-size: 50MB

mybatis:
  mapper-locations: classpath:mapping/*.xml

Note: The com.mysql.jdbc.Driver driver is used here, and an alarm will be reported when starting the project

Fourth, code combat

sql

DROP TABLE IF EXISTS `tbl_imageInfo`;
CREATE TABLE `tbl_imageInfo` (
                                 `id` int(11) NOT NULL AUTO_INCREMENT,
                                 `imgPath` varchar(300) NOT NULL,
                                 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

Controller

In order to avoid problems caused by uploading files with the same name, regenerate a random file name with UUID in the background to save

import com.pyy.service.ImageUploadService;
import com.pyy.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@RestController
public class UploadImageController {
    private static final Logger logger = LoggerFactory. getLogger(UploadImageController. class);

    @Autowired
    private ImageUploadService imageUploadService;

    @Value("${web.upload-path}")
    private String path;

    @Value("${server.port}")
    private String port;

    @PostMapping("fileUpload")
    public String upload(@RequestParam("file") MultipartFile file) {
        if (file. isEmpty()) {
            return "Upload file failed. File should not be empty.";
        }
        String contentType = file. getContentType();
        String fileName = file. getOriginalFilename();
        logger.error("Original file content type is {} name is: {}", contentType, fileName);
        String newRandomFileName = FileUtils.generateRandomFileName(fileName);
        try {
            FileUtils.upload(file, path, newRandomFileName);
        } catch (Exception e) {
            System.out.println("Upload file exception: " + e.getMessage());
        }

        return "Upload img success, please check the upload path!" + imageUploadService.imageUpload(path + File.separator + newRandomFileName);
    }
}

FileUtils

public class FileUtils {
    private static final Logger logger = LoggerFactory. getLogger(FileUtils. class);

    /**
     * @param file file
     * @param fileName new random file name
     */
    public static void upload(MultipartFile file, String destPath, String fileName) {
        File dest = new File(destPath + File.separator + fileName);
        / / Determine whether the parent directory of the file exists
        if (!dest. getParentFile(). exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            //save document
            file. transferTo(dest);
        } catch (Exception e) {
            logger.error("Save file exception. {}", e.getMessage());
        }

    }

    public static String getSuffix(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    public static String generateRandomFileName(String fileName) {
        return UUID. randomUUID() + getSuffix(fileName);
    }
}

Database mapping interface mapper

import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;

@Mapper
@Component
public interface UploadImageMapper {
    int insertImgPath(String imagePath);
}

Service: Call the database interface to save the file path

import com.pyy.mapper.UploadImageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("imageUploadService")
public class ImageUploadService {
    @Autowired
    private UploadImageMapper uploadImageMapper;

    public String imageUpload(String filePath) {
        int count = uploadImageMapper.insertImgPath(filePath);
        return count >= 1 ? "Upload success." : "Upload failed.";
    }
}

mybatis mapping xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.pyy.mapper.UploadImageMapper">
    <insert id="insertImgPath" parameterType="string">
        insert into tbl_imageInfo(imgPath) values (#{imagePath})
    </insert>
</mapper>

Home index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload Image</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="/fileUpload">
  Image<input id="file_upload" type="file" name="file" onchange="imgChange(this)"/>
  <input type="submit" value="upload"/>
</form>
<img id="uploaded_images" src="" style="width: 200px; height: 300px;" />
</body>

<script type="text/javascript">
  <!--Display the route that needs to upload pictures-->
  // select image to display
  function imgChange(obj) {
    // Get the clicked textbox
    var file = document. getElementById("file_upload");
    var imgUrl = window. URL. createObjectURL(file. files[0]);
    var img = document.getElementById('uploaded_images');
    img.setAttribute('src', imgUrl); // Modify img tag src attribute value
  };

</script>
</html>

5. Effect

After clicking upload, you can see a picture with a random name in the specified F:/zp/uploadImageDir directory,

Then query the database, you can see the path where the picture is saved