崔向南 | 03d21b9 | 2025-06-05 17:42:23 +0800 | [diff] [blame] | 1 | package bounty.service; |
| 2 | |
| 3 | import org.springframework.stereotype.Service; |
| 4 | import org.springframework.web.multipart.MultipartFile; |
| 5 | |
| 6 | import java.io.IOException; |
| 7 | import java.nio.file.Files; |
| 8 | import java.nio.file.Path; |
| 9 | import java.nio.file.Paths; |
| 10 | import java.util.UUID; |
| 11 | |
| 12 | @Service |
| 13 | public class FileStorageService { |
| 14 | public String saveFile(MultipartFile file) { |
| 15 | try { |
| 16 | // 1. 校验文件名非空 |
| 17 | String originalFilename = file.getOriginalFilename(); |
| 18 | if (originalFilename == null || originalFilename.isEmpty()) { |
| 19 | throw new IllegalArgumentException("上传文件名不能为空"); |
| 20 | } |
| 21 | |
| 22 | // 2. 生成唯一文件名 |
| 23 | String fileExtension = ""; |
| 24 | int dotIndex = originalFilename.lastIndexOf("."); |
| 25 | if (dotIndex > 0) { |
| 26 | fileExtension = originalFilename.substring(dotIndex); |
| 27 | } |
| 28 | String newFilename = UUID.randomUUID() + fileExtension; |
| 29 | |
| 30 | // 👇 新增:打印文件名生成结果(用于调试) |
| 31 | System.out.println("【生成文件名】" + newFilename); |
| 32 | |
| 33 | // 3. 指定存储路径 |
| 34 | Path uploadDir = Paths.get("uploads/"); |
| 35 | if (!Files.exists(uploadDir)) { |
| 36 | Files.createDirectories(uploadDir); |
| 37 | } |
| 38 | |
| 39 | // 👇 新增:打印完整路径(用于调试) |
| 40 | Path filePath = uploadDir.resolve(newFilename); |
| 41 | System.out.println("【文件保存路径】" + filePath.toAbsolutePath()); |
| 42 | |
| 43 | // 4. 写入文件 |
| 44 | Files.write(filePath, file.getBytes()); |
| 45 | |
| 46 | // 5. 返回访问路径 |
| 47 | return "/uploads/" + newFilename; |
| 48 | } catch (IOException e) { |
| 49 | // 👇 新增:记录异常信息 |
| 50 | System.err.println("【文件上传失败】" + e.getMessage()); |
| 51 | throw new RuntimeException("文件上传失败: " + e.getMessage(), e); |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |