添加上传最大值

This commit is contained in:
YY
2025-07-15 13:59:01 +08:00
parent fbea052fa2
commit 356f353a33
2 changed files with 21 additions and 2 deletions

View File

@ -18,26 +18,38 @@ public class FileStorageService {
@Value("${file.upload-dir}")
private String uploadDir;
private static final long MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB单位是字节
public String storeFile(MultipartFile file) {
// 检查文件大小
if (file.getSize() > MAX_FILE_SIZE) {
throw new RuntimeException("文件大小超过了最大限制10MB");
}
try {
String originalName = StringUtils.cleanPath(file.getOriginalFilename());
String ext = "";
// 获取文件扩展名
int i = originalName.lastIndexOf(".");
if (i >= 0) {
ext = originalName.substring(i);
}
// 生成新的文件名使用UUID来避免文件名冲突
String filename = UUID.randomUUID().toString() + ext;
Path copyLocation = Paths.get(uploadDir).toAbsolutePath().normalize().resolve(filename);
// 确保目标目录存在
Files.createDirectories(copyLocation.getParent());
// 将文件内容写入目标路径
Files.copy(file.getInputStream(), copyLocation, StandardCopyOption.REPLACE_EXISTING);
return filename;
} catch (IOException ex) {
throw new RuntimeException("Could not store file: " + ex.getMessage());
throw new RuntimeException("存储文件时出错: " + ex.getMessage());
}
}
}