| package com.example.myproject.controller; |
| |
| import cn.hutool.core.io.FileUtil; |
| import cn.hutool.core.lang.UUID; |
| import com.example.myproject.common.base.Result; |
| import org.springframework.web.bind.annotation.PostMapping; |
| import org.springframework.web.bind.annotation.RequestMapping; |
| import org.springframework.web.bind.annotation.RestController; |
| import org.springframework.web.multipart.MultipartFile; |
| |
| import java.nio.file.Files; |
| import java.nio.file.Path; |
| import java.nio.file.Paths; |
| |
| @RestController |
| @RequestMapping("/file") |
| public class FileController { |
| @PostMapping |
| public Result upload(MultipartFile file){ |
| try{ |
| String originalFilename = file.getOriginalFilename(); |
| String fileName = FileUtil.mainName(originalFilename) + UUID.fastUUID().toString() + "." + FileUtil.getSuffix(originalFilename); // 以用户ID作为文件名 |
| Path path = Paths.get("uploads/" + fileName); |
| Files.createDirectories(path.getParent()); |
| Files.write(path, file.getBytes()); |
| String filepath = "/uploads/" + fileName; |
| return Result.ok(filepath); // 返回相对URL路径 |
| |
| }catch (Exception ignore){ |
| return Result.failure("文件上传失败"); |
| } |
| |
| } |
| } |