创建表
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;
创建SpringBoot项目然后导入依赖
<?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>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<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;
}
创建Mapper
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> {
}
创建Service
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);
void download(String fileId, HttpServletResponse response);
}
创建ServiceImpl
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
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();
}
@Override
public void download(String fileId, HttpServletResponse response) {
File file = getById(fileId);
if (file == null) {
throw BizException.of("文件不存在");
}
java.io.File file1 = FileUtil.file(file.getPath());
//吧文件输出到响应流
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + file.getFilename());
try (
ServletOutputStream outputStream = response.getOutputStream();
) {
outputStream.write(FileUtil.readBytes(file1));
} catch (IOException e) {
throw BizException.of("文件下载失败");
}
}
}
创建Controller
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
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);
}
@GetMapping("/download/{fileId}")
public void download(@PathVariable String fileId, HttpServletResponse response) {
fileUploadService.download(fileId,response);
}
}
修改配置文件
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\\
评论区