FileUploadController.java 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. package com.izouma.nineth.web;
  2. import com.izouma.nineth.domain.FileObject;
  3. import com.izouma.nineth.exception.BusinessException;
  4. import com.izouma.nineth.service.storage.StorageService;
  5. import com.izouma.nineth.utils.ImageUtils;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.apache.commons.io.FileUtils;
  8. import org.apache.commons.io.FilenameUtils;
  9. import org.apache.commons.lang3.ArrayUtils;
  10. import org.apache.commons.lang3.RandomStringUtils;
  11. import org.apache.commons.lang3.StringUtils;
  12. import org.apache.poi.util.TempFile;
  13. import org.bytedeco.javacv.FFmpegFrameGrabber;
  14. import org.bytedeco.javacv.Frame;
  15. import org.bytedeco.javacv.Java2DFrameConverter;
  16. import org.springframework.beans.factory.annotation.Autowired;
  17. import org.springframework.web.bind.annotation.PostMapping;
  18. import org.springframework.web.bind.annotation.RequestMapping;
  19. import org.springframework.web.bind.annotation.RequestParam;
  20. import org.springframework.web.bind.annotation.RestController;
  21. import org.springframework.web.multipart.MultipartFile;
  22. import javax.imageio.ImageIO;
  23. import java.awt.image.BufferedImage;
  24. import java.io.*;
  25. import java.net.URLConnection;
  26. import java.text.SimpleDateFormat;
  27. import java.util.*;
  28. import java.util.regex.Pattern;
  29. @RestController
  30. @RequestMapping("/upload")
  31. @Slf4j
  32. public class FileUploadController {
  33. @Autowired
  34. private StorageService storageService;
  35. @PostMapping("/file")
  36. public String uploadFile(@RequestParam("file") MultipartFile file,
  37. @RequestParam(value = "path", required = false) String path,
  38. @RequestParam(value = "compress", defaultValue = "false") boolean compress,
  39. @RequestParam(value = "width", required = false) Integer width,
  40. @RequestParam(value = "height", required = false) Integer height) throws IOException {
  41. String ext = Optional.ofNullable(FilenameUtils.getExtension(file.getOriginalFilename())).orElse("")
  42. .toLowerCase().replace("jpeg", "jpg");
  43. if (path == null) {
  44. String basePath = Optional.ofNullable(file.getContentType()).orElse("application").split("/")[0];
  45. path = basePath + "/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
  46. + RandomStringUtils.randomAlphabetic(8)
  47. + "." + ext;
  48. }
  49. if (Pattern.matches("(jpg|png)", ext) && (compress || width != null || height != null)) {
  50. if (width == null && height == null) {
  51. width = Integer.MAX_VALUE;
  52. height = Integer.MAX_VALUE;
  53. } else if (height == null) {
  54. height = Integer.MAX_VALUE;
  55. } else if (width == null) {
  56. width = Integer.MAX_VALUE;
  57. }
  58. BufferedImage img = null;
  59. if ("jpg".equals(ext)) {
  60. img = ImageUtils.resizeJpg(file.getInputStream(), width, height, compress);
  61. } else if ("png".equals(ext)) {
  62. img = ImageUtils.resizePng(file.getInputStream(), width, height, compress);
  63. }
  64. Objects.requireNonNull(img, "图片压缩失败");
  65. ByteArrayOutputStream os = new ByteArrayOutputStream();
  66. ImageIO.write(img, ext, os);
  67. InputStream is = new ByteArrayInputStream(os.toByteArray());
  68. return storageService.uploadFromInputStream(is, path);
  69. }
  70. return storageService.uploadFromInputStream(file.getInputStream(), path);
  71. }
  72. @PostMapping("/base64")
  73. public String uploadImage(@RequestParam("base64") String base64,
  74. @RequestParam(value = "path", required = false) String path) {
  75. base64 = base64.substring(base64.indexOf(',') + 1);
  76. Base64.Decoder decoder = Base64.getDecoder();
  77. if (path == null) {
  78. String ext = ".jpg";
  79. try {
  80. InputStream is = new ByteArrayInputStream(decoder.decode(base64.getBytes()));
  81. String type = URLConnection.guessContentTypeFromStream(is);
  82. ext = type.replace("image/", ".").replace("jpeg", "jpg");
  83. } catch (Exception ignored) {
  84. }
  85. path = "image/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
  86. + RandomStringUtils.randomAlphabetic(8) + ext;
  87. }
  88. InputStream is;
  89. try {
  90. is = new ByteArrayInputStream(decoder.decode(base64.getBytes()));
  91. } catch (Exception e) {
  92. log.error("上传失败", e);
  93. throw new BusinessException("上传失败", e.getMessage());
  94. }
  95. return storageService.uploadFromInputStream(is, path);
  96. }
  97. @PostMapping("/fileObject")
  98. public FileObject uploadFileObject(@RequestParam("file") MultipartFile file,
  99. @RequestParam(value = "compress", defaultValue = "false") boolean compress,
  100. @RequestParam(value = "width", required = false) Integer width,
  101. @RequestParam(value = "height", required = false) Integer height) throws IOException {
  102. String ext = Optional.ofNullable(FilenameUtils.getExtension(file.getOriginalFilename())).orElse("")
  103. .toLowerCase().replace("jpeg", "jpg");
  104. String[] extList = new String[]{"jpg", "jpeg", "png", "gif", "mp4"};
  105. if (!ArrayUtils.contains(extList, ext.toLowerCase())) {
  106. throw new BusinessException("仅支持" + StringUtils.join(extList, "、") + "格式");
  107. }
  108. File tmpFile = File.createTempFile("upload_", "." + ext);
  109. FileUtils.copyToFile(file.getInputStream(), tmpFile);
  110. String path = "nft/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
  111. + RandomStringUtils.randomAlphabetic(8)
  112. + "." + ext;
  113. String url;
  114. if (Pattern.matches("(jpg|png)", ext) && (compress || width != null || height != null)) {
  115. if (width == null && height == null) {
  116. width = Integer.MAX_VALUE;
  117. height = Integer.MAX_VALUE;
  118. } else if (height == null) {
  119. height = Integer.MAX_VALUE;
  120. } else if (width == null) {
  121. width = Integer.MAX_VALUE;
  122. }
  123. BufferedImage img;
  124. if ("jpg".equals(ext)) {
  125. img = ImageUtils.resizeJpg(new FileInputStream(tmpFile), width, height, compress);
  126. } else {
  127. img = ImageUtils.resizePng(new FileInputStream(tmpFile), width, height, compress);
  128. }
  129. ByteArrayOutputStream os = new ByteArrayOutputStream();
  130. ImageIO.write(img, ext, os);
  131. InputStream is = new ByteArrayInputStream(os.toByteArray());
  132. url = storageService.uploadFromInputStream(is, path);
  133. } else {
  134. url = storageService.uploadFromInputStream(new FileInputStream(tmpFile), path);
  135. }
  136. String thumbUrl = null;
  137. if ("mp4".equalsIgnoreCase(ext)) {
  138. String thumbPath = "thumb_image/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
  139. + RandomStringUtils.randomAlphabetic(8) + ".jpg";
  140. FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(tmpFile);
  141. Java2DFrameConverter frameConverter = new Java2DFrameConverter();
  142. try {
  143. frameGrabber.start();
  144. Frame frame = null;
  145. while (frame == null) {
  146. frame = frameGrabber.grabKeyFrame();
  147. }
  148. Objects.requireNonNull(frame, "获取视频缩略图失败");
  149. BufferedImage thumbBi = frameConverter.convert(frame);
  150. BufferedImage thumbResized = ImageUtils.resizeJpg(thumbBi, 1000, 1000, false);
  151. ByteArrayOutputStream os = new ByteArrayOutputStream();
  152. ImageIO.write(thumbResized, "jpg", os);
  153. InputStream is = new ByteArrayInputStream(os.toByteArray());
  154. thumbUrl = storageService.uploadFromInputStream(is, thumbPath);
  155. } catch (Exception e) {
  156. e.printStackTrace();
  157. } finally {
  158. frameGrabber.stop();
  159. }
  160. }
  161. return new FileObject(file.getOriginalFilename(), url, thumbUrl, file.getContentType());
  162. }
  163. @PostMapping("/3dModel")
  164. public FileObject upload3dModel(@RequestParam("file") MultipartFile file) throws IOException {
  165. if (!"zip".equalsIgnoreCase(FilenameUtils.getExtension(file.getOriginalFilename()))) {
  166. throw new BusinessException("只能上传zip");
  167. }
  168. File destDir = TempFile.createTempDirectory(RandomStringUtils.randomAlphabetic(20));
  169. com.izouma.nineth.utils.FileUtils.unzip(file.getInputStream(), destDir);
  170. File fbxFile = com.izouma.nineth.utils.FileUtils.findInDir(destDir, ".fbx");
  171. if (fbxFile == null) {
  172. throw new BusinessException("找不到fbx文件");
  173. }
  174. File fbxDir = fbxFile.getParentFile();
  175. String basePath = "fbx/"
  176. + new SimpleDateFormat("yyyy-MM_dd-HH").format(new Date()) + "/"
  177. + RandomStringUtils.randomAlphabetic(16);
  178. List<String> urls = new ArrayList<>();
  179. for (File listFile : fbxDir.listFiles()) {
  180. if (!listFile.isHidden() && !listFile.isDirectory()) {
  181. urls.add(storageService.uploadFromInputStream(new FileInputStream(listFile), basePath + "/" + listFile.getName()));
  182. }
  183. }
  184. String fbxUrl = urls.stream().filter(s -> s.toLowerCase().endsWith(".fbx")).findAny()
  185. .orElseThrow(new BusinessException("找不到fbx文件"));
  186. return new FileObject(fbxFile.getName(), fbxUrl, null, "fbx");
  187. }
  188. }