controller多文件上传
@RequestMapping("upload")
public Result<OssFile> add(@RequestParam(value = "files") MultipartFile[] files,
@NotNull @NotEmpty(message = "文件夹不能为空") String fileDirId) {
ArrayList<OssFile> ossFiles = new ArrayList<>();
if (files != null && files.length > 0) {
for (MultipartFile file : files) {
OssFile ossFile = localOssService.upload(file);
ossFile.setFileDirId(fileDirId);
ossFile = ossFileService.save(ossFile);
ossFiles.add(ossFile);
}
}
}
localOssService
public OssFile upload(MultipartFile file) {
String staticPath = ClassUtils.getDefaultClassLoader().getResource("").getPath().replaceFirst("/", "");
try {
String type = FileTypeUtil.getType(file.getInputStream());
String fileType = MimeTypeUtil.imgOrVideo(type);
String uploadPath = "";
if (StrUtil.equals(fileType, FileType.IMAGE.getValue())) {
uploadPath = "upload/img/";
} else if (StrUtil.equals(fileType, FileType.VIDEO.getValue())) {
uploadPath = "upload/video/";
} else {
uploadPath = "upload/other";
}
String fileName = file.getOriginalFilename();
String name = file.getName();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
File file1 = new File(staticPath + uploadPath);
if (!file1.exists()) {
file1.mkdir();
}
if (fileName != null && !"".equals(fileName.trim())) {
String newName = UUID.randomUUID().toString().replace("-", "") + suffixName;
File desFile = new File(staticPath + uploadPath + File.separator + newName);
file.transferTo(desFile);
String fileUrl = staticPath + uploadPath + newName;
OssFile ossFile = new OssFile();
ossFile.setName(fileName);
ossFile.setMimeType(type);
ossFile.setFileType(FileType.valueOf(fileType));
ossFile.setFilename(fileName);
ossFile.setRealPath(uploadPath + newName);
ossFile.setUrl(fileUrl);
if (ObjectUtil.equal(FileType.VIDEO, FileType.valueOf(fileType))) {
ossFile.setCover("defaultURl");
}
return ossFile;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
MultipartFile常用方法
1、文件类型值 getContentType()
2、表单中文件组件对应name值 getName()
3、文件原始名称包括后缀名 getOriginalFilename()
4、文件大小单位为k getSize()
5、文件是否为空 isEmpty()
6、保存到一个目标文件中 transferTo()