|
|
@@ -0,0 +1,56 @@
|
|
|
+package com.etotem.num.service;
|
|
|
+
|
|
|
+import com.etotem.num.common.BizException;
|
|
|
+import org.springframework.stereotype.Service;
|
|
|
+import org.springframework.web.multipart.MultipartFile;
|
|
|
+
|
|
|
+import java.io.IOException;
|
|
|
+import java.nio.file.Files;
|
|
|
+import java.nio.file.Path;
|
|
|
+import java.util.Arrays;
|
|
|
+import java.util.List;
|
|
|
+import java.util.UUID;
|
|
|
+
|
|
|
+@Service
|
|
|
+public class UploadService {
|
|
|
+
|
|
|
+ private final Path uploadPath;
|
|
|
+
|
|
|
+ private static final long MAX_FILE_SIZE = 10 * 1024 * 1024;
|
|
|
+
|
|
|
+ private static final List<String> SUPPORTED_EXTENSIONS = Arrays.asList("amr", "mp3", "wav", "sil");
|
|
|
+
|
|
|
+ public UploadService(Path uploadPath) {
|
|
|
+ this.uploadPath = uploadPath;
|
|
|
+ }
|
|
|
+
|
|
|
+ public String storeAudio(MultipartFile file, Long userId) {
|
|
|
+ if (file.isEmpty()) {
|
|
|
+ throw new BizException(400, "文件为空");
|
|
|
+ }
|
|
|
+ if (file.getSize() > MAX_FILE_SIZE) {
|
|
|
+ throw new BizException(400, "文件大小不能超过10MB");
|
|
|
+ }
|
|
|
+
|
|
|
+ String originalName = file.getOriginalFilename();
|
|
|
+ String ext = "";
|
|
|
+ if (originalName != null && originalName.contains(".")) {
|
|
|
+ ext = originalName.substring(originalName.lastIndexOf(".") + 1).toLowerCase();
|
|
|
+ }
|
|
|
+ if (!SUPPORTED_EXTENSIONS.contains(ext)) {
|
|
|
+ throw new BizException(400, "不支持的文件格式,仅支持: amr, mp3, wav, sil");
|
|
|
+ }
|
|
|
+
|
|
|
+ String filename = System.currentTimeMillis() + "_" + UUID.randomUUID().toString().replace("-", "") + "." + ext;
|
|
|
+ Path userDir = uploadPath.resolve("audio").resolve(String.valueOf(userId));
|
|
|
+
|
|
|
+ try {
|
|
|
+ Files.createDirectories(userDir);
|
|
|
+ Files.copy(file.getInputStream(), userDir.resolve(filename));
|
|
|
+ } catch (IOException e) {
|
|
|
+ throw new BizException(500, "文件上传失败");
|
|
|
+ }
|
|
|
+
|
|
|
+ return "/uploads/audio/" + userId + "/" + filename;
|
|
|
+ }
|
|
|
+}
|