首先建立测试用的数据库
CREATE TABLE `file` (
`id` bigint NOT NULL COMMENT '主键',
`filename` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '文件名',
`filepath` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '文件路径',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
创建完成后是这样
然后去引入依赖
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
runtime
8.0.26
org.projectlombok
lombok
true
com.baomidou
mybatis-plus-boot-starter
3.0-RELEASE
com.baomidou
mybatis-plus-generator
3.0-RELEASE
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.2.0
org.springframework.boot
spring-boot-starter-freemarker
io.springfox
springfox-swagger2
3.0.0
io.springfox
springfox-swagger-ui
2.9.2
com.alibaba
fastjson
1.2.76
记得指定文件扫描路径
src/main/java
**/*.properties
**/*.yml
**/*.xml
false
src/main/resources
**/*.properties
**/*.yml
**/*.xml
false
org.springframework.boot
spring-boot-maven-plugin
org.projectlombok
lombok
然后去配置application.yml
# 配置服务端口
server:
port: 8081
# 配置数据库连接池
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/fileupload?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&allowPublicKeyRetrieval=true
username: root
password: root
# 配置文件上传大小和总上传文件大小
servlet:
multipart:
max-file-size: 100MB
max-request-size: 1000MB
# mybatis-plus的配置
mybatis-plus:
# config-location: classpath:myabtis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*Mapper.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
去新建一个util包,配置Mybatis Plus的代码生成器
不会用的小伙伴可以去看我的这篇文章https://blog.csdn.net/HackAzrael/article/details/120984912https://blog.csdn.net/HackAzrael/article/details/120984912
因为代码生成器里配置了开启swagger注解,所以去新建一个config包,在里面编写swagger的配置
package com.study.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket createRestApi() {
System.out.println("====== SWAGGER CONFIG ======");
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.study"))
.paths(PathSelectors.any()) // 可以根据url路径设置哪些请求加入文档,忽略哪些请求
.build().useDefaultResponseMessages(false);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("文件上传及下载 APIs")
.build();
}
// @Bean
// public JwtUtils jwtUtils() {
// return new JwtUtils();
// }
// @Bean
// public PaginationInterceptor paginationInterceptor() {
// return new PaginationInterceptor();
// }
}
然后回车就可以自动生成对应的表的控制层、业务层、数据层等等,生成完是这样的
下面进入正文!!
entity
package com.study.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 文件上传下载实体类
* @author az
* @since 2021-10-26
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("file")
@ApiModel(value="File对象")
public class File implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@ApiModelProperty(value = "主键")
private Long id;
/**
* 文件名
*/
@ApiModelProperty(value = "文件名")
private String filename;
/**
* 文件路径
*/
@ApiModelProperty(value = "文件路径")
@TableField("filePath")
private String filepath;
}
controller
package com.study.controller;
import com.alibaba.fastjson.JSON;
import com.study.entity.File;
import com.study.service.FileService;
import com.study.util.Result;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
/**
* 文件上传下载控制层
* @author az
* @since 2021-10-26
*/
@RestController
@RequestMapping("/file")
public class FileController {
@Resource
private FileService fileService;
/**
* 文件上传
* @param multipartFile 上传的文件
* @param file file表实体类
* @return 成功 or 失败的信息
*/
@ApiOperation("文件上传")
@ApiResponses({
@ApiResponse(code = 200, message = "上传成功"),
@ApiResponse(code = 510, message = "上传失败")
})
@PostMapping("/fileUpload")
public String fileUpload(@RequestParam("file") MultipartFile multipartFile, File file){
int res = fileService.uploadFile(multipartFile,file);
Map map = new HashMap<>();
//判断是否执行成功
if (res > 0){
map.put(Result.CODE,200);
map.put(Result.SUCCESS,true);
map.put(Result.MESSAGE,"上传成功");
}else {
map.put(Result.CODE,510);
map.put(Result.SUCCESS,false);
map.put(Result.MESSAGE,"上传失败");
}
return JSON.toJSONString(map);
}
}
service
package com.study.service;
import com.study.entity.File;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.web.multipart.MultipartFile;
/**
* 文件上传下载业务层
* @author az
* @since 2021-10-26
*/
public interface FileService extends IService {
/**
* 上传文件
* @param multipartFile 上传的文件
* @param file 上传的文件
* @return 0 or 1
*/
int uploadFile(MultipartFile multipartFile,File file);
}
serviceImpl
package com.study.service.impl;
import com.study.entity.File;
import com.study.mapper.FileMapper;
import com.study.service.FileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.util.FileUtils;
import com.study.util.SnowflakeIdUtils;
import com.study.util.UUIDUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
/**
* 文件上传下载业务实现层
* @author az
* @since 2021-10-26
*/
@Service
@Transactional
public class FileServiceImpl extends ServiceImpl implements FileService {
@Resource
private FileMapper fileMapper;
@Override
public int uploadFile(MultipartFile multipartFile, File file) {
if (!multipartFile.isEmpty()){
//将UUID设置为主键id
SnowflakeIdUtils idUtils = new SnowflakeIdUtils(11,18);
long id = idUtils.nextId();
file.setId(id);
//获取文件的前后缀名
String name = multipartFile.getOriginalFilename();
file.setFileName(name);
//获取文件后缀名
String[] suffix = name.split("\\.");
int suffixIndex = suffix.length - 1;
//随机生成UUID为文件名并保存到数据库
String name = UUIDUtils.getUUID() + "." + suffix[suffixIndex];
//设置文件上传路径
String path = "D:\\uploadFile\\";
try {
//调用工具类上传文件
String filePath = FileUtils.uploadFile(multipartFile.getBytes(), path, name);
file.setFilepath(filePath);
} catch (Exception e){
return 0;
}
//使用Mybatis Plus自带的新增方法进行插入
return fileMapper.insert(file);
}else {
return 0;
}
}
}
mapper
package com.study.mapper;
import com.study.entity.File;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* 文件上传下载Mapper 接口
* @author az
* @since 2021-10-26
*/
public interface FileMapper extends BaseMapper{
}
FileUtils //主要用来实现文件上传到服务器
package com.study.util;
import java.io.File;
import java.io.FileOutputStream;
/**
* @Author: az
* @Data: 2021/10/26
* 文件工具类
*/
public class FileUtils {
public static String uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
//父目录不存在则创建
if(!targetFile.exists()){
targetFile.mkdirs();
}
//使用UUID重命名以免文件名重复
String dest = filePath + fileName;
FileOutputStream out = new FileOutputStream(dest);
out.write(file);
out.flush();
out.close();
return dest;
}
}
SnowflakeIdUtils //主要用来实现自动生成雪花id
不会的小伙伴依旧可以去看我的这篇文章
https://blog.csdn.net/HackAzrael/article/details/120984980https://blog.csdn.net/HackAzrael/article/details/120984980
UUIDUtils //主要用来实现随机生成UUID
package com.study.util;
import java.util.UUID;
/**
* @ClassName UUIDUtils
* @Description TODO
* @Author Az
* @Date 2021-10-26 23:00
*/
public class UUIDUtils {
public static String getUUID(){
return UUID.randomUUID().toString().replace("-","");
}
}
Result //放在荷载里,主要用来返回给前端信息
package com.study.util;
/**
* @author Az
* @Description TODO
* @date 2021-10-26
*/
public interface Result {
/**
* 状态码
*/
String CODE = "code";
/**
* 是否成功
*/
String SUCCESS = "success";
/**
* 返回信息
*/
String MESSAGE = "message";
}
一切搞定,直接运行!对了,可别忘了在Application上加MapperScan注解
运行完成后用swagger或者postman测一下方法是否能正常执行,我这里用的是postman
填写完路径后选Body,然后去填代码里在@RequestParam指定的名字,我这里是叫file,接着类型选择File(默认为Text),然后去Select File选择要上传的文件,最后send,上传成功!
再来看一下路径里是否有文件
可以看到本地是可以正常接收到文件的,再来看一下数据库
数据库中也有对应的数据
至此文件上传并保存数据库就完美结束啦!