스pringboot 파일 업로드

스pringboot 파일 업로드

데이터베이스 테이블 생성

DROP TABLE IF EXISTS `file`;
CREATE TABLE `file`  (
  `id` int(0) NOT NULL,
  `filename` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '파일명',
  `path` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '파일 경로',
  `status` int(0) NULL DEFAULT NULL COMMENT '파일 상태 1: 삭제 0: 정상',
  `create_time` datetime(0) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

Spring Boot 프로젝트 생성 및 의존성 추가

<?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>3.1.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>top.gaoqiulin</groupId>
    <artifactId>fileupload</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>fileupload</name>
    <description>fileupload</description>
    <properties>
        <java.version>21</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.30</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.25</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

모델 클래스 정의

통일된 결과 클래스

import lombok.Data;
import java.io.Serializable;

@Data
public class Result implements Serializable {
    private static final long serialVersionUID = 1L;
    
    private Integer code;
    
    private String msg;
    
    private Object data;

    public Result(Integer code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
    public Result(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }
    public Result(Integer code) {
        this.code = code;
    }
}

비즈니스 예외 클래스

import lombok.Data;

@Data
public class BizException extends RuntimeException {
    private Integer code;
    private String msg;

    public static BizException of(Integer code, String msg) {
        BizException bizException = new BizException();
        bizException.setCode(code);
        bizException.setMsg(msg);
        return bizException;
    }

    public static BizException of(String msg) {
        BizException bizException = new BizException();
        bizException.setCode(500);
        bizException.setMsg(msg);
        return bizException;
    }
}

파일 엔티티 클래스

import lombok.Data;
import java.io.Serializable;
import java.util.Date;

@Data
public class File implements Serializable {
    private static final long serialVersionUID = 1L;
    private String id;
    private String filename;
    private String path;
    private Integer status;
    private Date createTime;
}

파일 업로드 맵퍼 인터페이스

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import top.gaoqiulin.fileupload.domain.entity.File;

@Mapper
public interface FileUploadMapper extends BaseMapper<File> {
}

파일 업로드 서비스 인터페이스

import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.web.multipart.MultipartFile;
import top.gaoqiulin.fileupload.domain.entity.File;

public interface FileUploadService extends IService<File> {
    String upload(MultipartFile file);
}

파일 업로드 서비스 인plement

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.gaoqiulin.fileupload.domain.entity.File;
import top.gaoqiulin.fileupload.exception.BizException;
import top.gaoqiulin.fileupload.mapper.FileUploadMapper;
import top.gaoqiulin.fileupload.service.FileUploadService;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class FileUploadServiceImpl extends ServiceImpl<FileUploadMapper, File> implements FileUploadService {
    @Resource
    private FileUploadMapper fileUploadMapper;

    @Value("${upload}")
    private String upload;

    @Override
    public String upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String mainName = FileUtil.mainName(originalFilename);
        String extName = FileUtil.extName(originalFilename);
        String fileName = mainName + UUID.randomUUID().toString().replaceAll("-", "") + "." + extName;

        String absolutePath = upload + fileName;

        try {
            FileUtil.writeBytes(file.getBytes(), absolutePath);
        } catch (IOException e) {
            log.error("파일 업로드 실패 {}", e.getMessage());
            throw BizException.of("파일 업로드 실패");
        }
        File fileUpload = new File();
        fileUpload.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        fileUpload.setFilename(fileName);
        fileUpload.setPath(absolutePath);
        fileUpload.setStatus(0);
        fileUpload.setCreateTime(new Date());
        save(fileUpload);
        return fileUpload.getId();
    }
}

컨트롤러

import jakarta.annotation.Resource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.gaoqiulin.fileupload.service.FileUploadService;
import top.gaoqiulin.fileupload.utils.Result;

@RequestMapping("/file")
@RestController
public class FileController {
    @Resource
    private FileUploadService fileUploadService;

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result upload(@RequestPart("file") MultipartFile file) {
        String fileId = fileUploadService.upload(file);
        return new Result(200, "업로드 성공", fileId);
    }
}

애플리케이션.properties 파일 설정

spring.application.name=fileupload
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/fileupload?serverTimeZone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
upload=D:\\idea\\workspace\\fileupload\\fileupload\\src\\main\\resources\\upload\\

태그: spring-boot file-upload MySQL MyBatis-Plus

7월 15일 22:37에 게시됨