| package bounty.service; |
| |
| import org.springframework.stereotype.Service; |
| import org.springframework.web.multipart.MultipartFile; |
| |
| import java.io.IOException; |
| import java.nio.file.Files; |
| import java.nio.file.Path; |
| import java.nio.file.Paths; |
| import java.util.UUID; |
| |
| @Service |
| public class FileStorageService { |
| public String saveFile(MultipartFile file) { |
| try { |
| // 1. 校验文件名非空 |
| String originalFilename = file.getOriginalFilename(); |
| if (originalFilename == null || originalFilename.isEmpty()) { |
| throw new IllegalArgumentException("上传文件名不能为空"); |
| } |
| |
| // 2. 生成唯一文件名 |
| String fileExtension = ""; |
| int dotIndex = originalFilename.lastIndexOf("."); |
| if (dotIndex > 0) { |
| fileExtension = originalFilename.substring(dotIndex); |
| } |
| String newFilename = UUID.randomUUID() + fileExtension; |
| |
| // 👇 新增:打印文件名生成结果(用于调试) |
| System.out.println("【生成文件名】" + newFilename); |
| |
| // 3. 指定存储路径 |
| Path uploadDir = Paths.get("uploads/"); |
| if (!Files.exists(uploadDir)) { |
| Files.createDirectories(uploadDir); |
| } |
| |
| // 👇 新增:打印完整路径(用于调试) |
| Path filePath = uploadDir.resolve(newFilename); |
| System.out.println("【文件保存路径】" + filePath.toAbsolutePath()); |
| |
| // 4. 写入文件 |
| Files.write(filePath, file.getBytes()); |
| |
| // 5. 返回访问路径 |
| return "/uploads/" + newFilename; |
| } catch (IOException e) { |
| // 👇 新增:记录异常信息 |
| System.err.println("【文件上传失败】" + e.getMessage()); |
| throw new RuntimeException("文件上传失败: " + e.getMessage(), e); |
| } |
| } |
| } |
| |