|
@@ -4,11 +4,16 @@ import java.io.IOException;
|
|
|
import java.io.InputStream;
|
|
|
|
|
|
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;
|
|
@@ -21,6 +26,7 @@ import org.springframework.web.multipart.MultipartFile;
|
|
|
* @author Woody
|
|
|
* @date 2023/5/4
|
|
|
*/
|
|
|
+@Slf4j
|
|
|
@Validated
|
|
|
@RestController
|
|
|
@ResponseWrapping
|
|
@@ -28,6 +34,25 @@ import org.springframework.web.multipart.MultipartFile;
|
|
|
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) {
|
|
|
+ if (log.isDebugEnabled()) {
|
|
|
+ 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);
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* 上传文件
|
|
|
*
|
|
@@ -36,10 +61,13 @@ public class FileController {
|
|
|
* @throws IOException I/O异常
|
|
|
*/
|
|
|
@PostMapping("/file")
|
|
|
- public String upload(@RequestParam("file") MultipartFile file) throws IOException {
|
|
|
- String suffix = StringUtils.ifEmpty(file.getOriginalFilename(), FileUtils::getSuffix);
|
|
|
+ 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()) {
|
|
|
- return this.uploadHandler.upload(stream, suffix);
|
|
|
+ String url = this.uploadHandler.upload(stream, suffix);
|
|
|
+ return File.builder().name(filename).media(media).url(url).build();
|
|
|
}
|
|
|
}
|
|
|
}
|