1.controller代码
java
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {
/**
* 本地存储
*/
@PostMapping("/upload")
@ApiOperation("本地文件上传")
public Result<String> upload(MultipartFile file){
log.info("本地文件上传:{}",file);
try {
//1.创建存储文件夹,不存在自动生成
File folder = new File(basePath);
if(!folder.exists()){
folder.mkdirs();
}
//2.获取文件原始名 + 后缀
String originalName = file.getOriginalFilename();
String suffix = originalName.substring(originalName.lastIndexOf("."));
//3.UUID生成唯一文件名,避免重名覆盖
String fileName = UUID.randomUUID() + suffix;
//4.拼接完整本地文件路径
File targetFile = new File(basePath + fileName);
//5.写入本地磁盘
file.transferTo(targetFile);
//6.拼接前端可访问的URL,返回给前端保存到数据库
String url = domain + baseUrl + fileName;
log.info("本地文件url路径:{}",url);
return Result.success(url);
} catch (IOException e) {
e.printStackTrace();
return Result.error("文件上传失败");
}
}
}
2.配置文件代码:
java
@Value("${sky.local-file.base-path}")
private String basePath;
@Value("${sky.local-file.base-url}")
private String baseUrl;
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(baseUrl + "**").addResourceLocations("file:" + basePath);
}
这里注意:
- 类上一定要标注@Configuration注解
- file后一定不要忘了冒号:
3.配置一些参数:
java
sky:
local-file:
# 本地文件存储路径
base-path: D:/sky_upload/
# 前端访问资源映射前缀
base-url: /upload/
# 本地服务访问域名
domain: http://localhost:8080