添加上传最大值
This commit is contained in:
@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user