Jin | f50fba6 | 2025-06-09 22:47:24 +0800 | [diff] [blame] | 1 | package com.example.myproject.controller; |
| 2 | |
| 3 | import cn.hutool.core.io.FileUtil; |
| 4 | import cn.hutool.core.lang.UUID; |
| 5 | import com.example.myproject.common.base.Result; |
| 6 | import org.springframework.web.bind.annotation.PostMapping; |
| 7 | import org.springframework.web.bind.annotation.RequestMapping; |
| 8 | import org.springframework.web.bind.annotation.RestController; |
| 9 | import org.springframework.web.multipart.MultipartFile; |
| 10 | |
| 11 | import java.nio.file.Files; |
| 12 | import java.nio.file.Path; |
| 13 | import java.nio.file.Paths; |
| 14 | |
| 15 | @RestController |
| 16 | @RequestMapping("/file") |
| 17 | public class FileController { |
| 18 | @PostMapping |
| 19 | public Result upload(MultipartFile file){ |
| 20 | try{ |
| 21 | String originalFilename = file.getOriginalFilename(); |
| 22 | String fileName = FileUtil.mainName(originalFilename) + UUID.fastUUID().toString() + "." + FileUtil.getSuffix(originalFilename); // 以用户ID作为文件名 |
| 23 | Path path = Paths.get("uploads/" + fileName); |
| 24 | Files.createDirectories(path.getParent()); |
| 25 | Files.write(path, file.getBytes()); |
| 26 | String filepath = "/uploads/" + fileName; |
| 27 | return Result.ok(filepath); // 返回相对URL路径 |
| 28 | |
| 29 | }catch (Exception ignore){ |
| 30 | return Result.failure("文件上传失败"); |
| 31 | } |
| 32 | |
| 33 | } |
| 34 | } |