AudioController.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package com.njuzr.eaibackend.controller;
  2. import com.njuzr.eaibackend.utils.OssUtil;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.*;
  6. import org.springframework.web.multipart.MultipartFile;
  7. import java.io.IOException;
  8. /**
  9. * @author Liululin
  10. * @date 2025/1/21 - 18:54
  11. */
  12. @RestController
  13. @Slf4j
  14. @RequestMapping("/api/audio")
  15. public class AudioController {
  16. private final OssUtil ossUtil;
  17. @Autowired
  18. public AudioController(OssUtil ossUtil) {
  19. this.ossUtil = ossUtil;
  20. }
  21. /**
  22. * 上传音频文件
  23. * @param file MultipartFile 音频文件
  24. * @return 上传后的文件 URL
  25. * @throws IOException 上传失败时抛出
  26. */
  27. @PostMapping
  28. public MyResponse uploadAudio(@RequestParam("file") MultipartFile file) throws IOException {
  29. // 校验文件格式
  30. String originalFilename = file.getOriginalFilename();
  31. if (originalFilename == null ||
  32. (!originalFilename.endsWith(".mp3") && !originalFilename.endsWith(".wav"))) {
  33. return MyResponse.error(500,"文件格式不支持,仅支持 mp3 和 wav 格式");
  34. }
  35. // 定义存储路径
  36. String filePath = "audio/" + originalFilename;
  37. // 上传文件到 OSS
  38. String url = ossUtil.uploadFile(file.getInputStream(), filePath);
  39. log.info("url:" + url);
  40. // 返回文件 URL
  41. return MyResponse.success(url);
  42. }
  43. /**
  44. * 获取音频文件列表
  45. * @return 文件列表
  46. */
  47. @GetMapping
  48. public MyResponse getAudioFiles() {
  49. // 获取 OSS 中 audio 目录下的文件列表
  50. return MyResponse.success(ossUtil.listFiles());
  51. }
  52. /**
  53. * 删除指定音频文件
  54. * @param filePath 文件路径
  55. * @return 删除结果
  56. */
  57. @DeleteMapping
  58. public MyResponse deleteAudio(@RequestParam String filePath) {
  59. // 删除文件
  60. ossUtil.deleteFile(filePath);
  61. return MyResponse.success("音频文件删除成功");
  62. }
  63. }