Java MultipartFile 使用记录

private void file(String path,MultipartFile file){
String separator = "/";
String originFileName = file.getOriginalFilename();//文件名称
String suffix = FileType.getSuffixByFilename(originFileName); //文件类型
originFileName = originFileName.substring(0, originFileName.length() - suffix.length()); //文件名称

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String dateString = sdf.format(new Date());
StringBuffer filePath = new StringBuffer();
filePath.append(path).append(File.separator).append(dateString).append(File.separator);

File physicalPath = new File(filePath.toString());//创建文件存储位置
if (!physicalPath.exists()) physicalPath.mkdirs();
String newName = UUID.randomUUID().toString().replaceAll("-", "") + suffix; //随机生成文件名称
String physicalFileString = physicalPath.getAbsolutePath() + File.separator + newName; //文件存储位置

// 转存文件
File localFile = new File(physicalFileString); //创建文件对象
try {
file.transferTo(localFile); //文件写入新路径中
} catch (IOException e) {
e.printStackTrace();
}
StringBuffer fileUrl = new StringBuffer(dateString).append(separator).append(newName); //文件存储位置
}

存储多个文件使用 MultipartFile[] 遍历循环每个文件保存



原文地址:https://www.cnblogs.com/lixxx/p/10648596.html