FileController.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package com.supervision.web.noticeManage.controller;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.http.ResponseEntity;
  4. import org.springframework.util.StringUtils;
  5. import org.springframework.web.bind.annotation.*;
  6. import org.springframework.web.multipart.MultipartFile;
  7. import java.io.*;
  8. import java.nio.file.*;
  9. import java.time.LocalDate;
  10. import java.time.format.DateTimeFormatter;
  11. import java.util.*;
  12. @RestController
  13. @RequestMapping("/notice")
  14. public class FileController {
  15. @Value("${file.upload-dir}")
  16. private String uploadDir;
  17. @Value("${file.url-prefix}")
  18. private String urlPrefix;
  19. @PostMapping("/upload")
  20. public ResponseEntity<?> upload(@RequestParam("file") MultipartFile file) {
  21. if (file == null || file.isEmpty()) {
  22. return ResponseEntity.badRequest().body(Collections.singletonMap("message", "文件为空"));
  23. }
  24. try {
  25. // 按日期分目录: yyyy/MM/dd
  26. String sub = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
  27. Path dir = Paths.get(uploadDir, sub);
  28. if (!Files.exists(dir)) Files.createDirectories(dir);
  29. String original = StringUtils.cleanPath(Objects.requireNonNull(file.getOriginalFilename()));
  30. String ext = "";
  31. int idx = original.lastIndexOf('.');
  32. if (idx >= 0) ext = original.substring(idx);
  33. String filename = UUID.randomUUID().toString().replace("-", "") + ext;
  34. Path target = dir.resolve(filename);
  35. try (InputStream in = file.getInputStream()) {
  36. Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
  37. }
  38. // 返回相对 URL:/files/yyyy/MM/dd/filename.ext
  39. String fileUrl = urlPrefix + "/" + sub + "/" + filename;
  40. Map<String, Object> body = new HashMap<>();
  41. body.put("url", fileUrl);
  42. body.put("contentType", file.getContentType());
  43. return ResponseEntity.ok(body);
  44. } catch (IOException e) {
  45. e.printStackTrace();
  46. return ResponseEntity.status(500).body(Collections.singletonMap("message", "上传失败"));
  47. }
  48. }
  49. }