|
@@ -0,0 +1,71 @@
|
|
|
+package com.chelvc.cloud.admin.controller;
|
|
|
+
|
|
|
+import com.chelvc.framework.base.annotation.ResponseWrapping;
|
|
|
+import com.chelvc.framework.common.model.File;
|
|
|
+import com.chelvc.framework.common.model.Media;
|
|
|
+import com.chelvc.framework.common.util.FileUtils;
|
|
|
+import com.chelvc.framework.common.util.ObjectUtils;
|
|
|
+import com.chelvc.framework.common.util.StringUtils;
|
|
|
+import com.chelvc.framework.upload.UploadHandler;
|
|
|
+import lombok.RequiredArgsConstructor;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
|
+import org.springframework.http.MediaType;
|
|
|
+import org.springframework.validation.annotation.Validated;
|
|
|
+import org.springframework.web.bind.annotation.PostMapping;
|
|
|
+import org.springframework.web.bind.annotation.RequestParam;
|
|
|
+import org.springframework.web.bind.annotation.RestController;
|
|
|
+import org.springframework.web.multipart.MultipartFile;
|
|
|
+
|
|
|
+import java.io.IOException;
|
|
|
+import java.io.InputStream;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 文件接口
|
|
|
+ *
|
|
|
+ * @author Woody
|
|
|
+ * @date 2023/5/4
|
|
|
+ */
|
|
|
+@Slf4j
|
|
|
+@Validated
|
|
|
+@RestController
|
|
|
+@ResponseWrapping
|
|
|
+@RequiredArgsConstructor(onConstructor = @__(@Autowired))
|
|
|
+public class FileController {
|
|
|
+ private final UploadHandler uploadHandler;
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 获取文件媒体类型
|
|
|
+ *
|
|
|
+ * @param file 文件对象
|
|
|
+ * @return 媒体类型
|
|
|
+ */
|
|
|
+ private Media getMedia(MultipartFile file) {
|
|
|
+ MediaType type = null;
|
|
|
+ try {
|
|
|
+ type = StringUtils.ifEmpty(file.getContentType(), MediaType::parseMediaType);
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.debug("Media type parse failed: {}", e.getMessage());
|
|
|
+ }
|
|
|
+ String value = StringUtils.ifEmpty(StringUtils.ifEmpty(type, MediaType::getType), String::toUpperCase);
|
|
|
+ return ObjectUtils.ifNull(StringUtils.ifEmpty(value, Media::parse), Media.NORMAL);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 上传文件
|
|
|
+ *
|
|
|
+ * @param file 文件对象
|
|
|
+ * @return 文件地址
|
|
|
+ * @throws IOException I/O异常
|
|
|
+ */
|
|
|
+ @PostMapping("/file")
|
|
|
+ public File upload(@RequestParam("file") MultipartFile file) throws IOException {
|
|
|
+ Media media = this.getMedia(file);
|
|
|
+ String filename = file.getOriginalFilename();
|
|
|
+ String suffix = StringUtils.ifEmpty(filename, FileUtils::getSuffix);
|
|
|
+ try (InputStream stream = file.getInputStream()) {
|
|
|
+ String url = this.uploadHandler.upload(stream, suffix);
|
|
|
+ return File.builder().name(filename).media(media).url(url).build();
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|