首先,工具类,我这里想用一个单独的文件夹放图片,一个单独的文件夹放视频,因此对两者进行后缀名校验,如果属于视频就放入video文件夹,如果是图片就放入picture文件夹,而两者的虚拟路径映射也是自定义,进行分别之后进行url拼接
@Component
public class FileUpload {
@Value("${imgPath}")
private String imgPath;
@Value("${videoPath}")
private String videoPath;
@Value("${virtualVideoUrl}")
private String virtualVideoUrl;
@Value("${virtualImgUrl}")
private String virtualImgUrl;
//图片格式
private final static String[] IMG_TYPES = new String[]{
"jpg", "bmp", "jpeg", "png", "gif",
"JPG", "BMP", "JPEG", "PNG", "GIF"
};
//视频格式
private final static String[] VIDEO_TYPES = new String[]{
"flv", "mp5","mp4","mpg","mpeg","avi","rm","rmvb","mov","wmv","asf","dat"
};
public String uploadFile(MultipartFile file) throws IOException {
boolean flag = false,flag1 = false;
if (file != null) {
if(file.getOriginalFilename()!=null && !file.getOriginalFilename().equals("")) {
String suffix = file.getOriginalFilename().split("\\.")[1];
for (String imgType : IMG_TYPES) {
if (suffix.equals(imgType)) {
flag = true;
break;
}
}
//如果为真证明是图片
if (flag) {
return groupByFile(virtualImgUrl,file,imgPath);
}
for (String videoType : VIDEO_TYPES) {
if(suffix.equals(videoType)){
flag1 = true;
break;
}
}
if(flag1){
return groupByFile(virtualVideoUrl,file,videoPath);
}
}
}
throw new RuntimeException("没有匹配的文件路径");
}
public String groupByFile(String url_perfix,MultipartFile file, String path) throws IOException {
String fileName = System.currentTimeMillis() + file.getOriginalFilename();
String upload_file_dir = path;
String destFileName = path + fileName;
File upload_file_dir_file = new File(upload_file_dir);
if (!upload_file_dir_file.exists()) {
upload_file_dir_file.mkdirs();
}
File targetFile = new File(upload_file_dir_file, fileName);
file.transferTo(targetFile);
return url_perfix+fileName;
}
}
mvc配置类,springboot2.6.x版本的mvc配置稍微有点区别,需要配置ant_path_matcher
文件上传需要限制大小
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
servlet:
multipart:
max-file-size: 1024MB
max-request-size: 1024MB
@Configuration
public class MyMVCconfig implements WebMvcConfigurer {
//修改虚拟路径映射到本机,依次映射视频和图片路径
@Value("${imgPath}")
private String imgPath;
@Value("${videoPath}")
private String videoPath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**").addResourceLocations(
"file:"+imgPath
);
registry.addResourceHandler("/video/**").addResourceLocations(
"file:"+videoPath
);
}
}
控制层
@Api("文件有关接口")
@RestController
@RequestMapping("/file")
public class FileController{
@Autowired
private FileUpload fileUpload;
@ApiOperation("上传文件")
@RequestMapping(value = "/upload",method = RequestMethod.POST)
public RespBean uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
String url = fileUpload.uploadFile(file);
if(url.contains("//")){
return RespBean.success("上传成功",url);
}
return RespBean.error("上传失败");
}
}