FileUploadController.java 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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.bytedeco.javacv.FFmpegFrameGrabber;
  13. import org.bytedeco.javacv.Frame;
  14. import org.bytedeco.javacv.Java2DFrameConverter;
  15. import org.pngquant.PngQuant;
  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.Base64;
  28. import java.util.Date;
  29. import java.util.Objects;
  30. import java.util.Optional;
  31. import java.util.regex.Pattern;
  32. @RestController
  33. @RequestMapping("/upload")
  34. @Slf4j
  35. public class FileUploadController {
  36. @Autowired
  37. private StorageService storageService;
  38. @PostMapping("/file")
  39. public String uploadFile(@RequestParam("file") MultipartFile file,
  40. @RequestParam(value = "path", required = false) String path,
  41. @RequestParam(value = "compress", defaultValue = "false") boolean compress,
  42. @RequestParam(value = "width", required = false) Integer width,
  43. @RequestParam(value = "height", required = false) Integer height) throws IOException {
  44. String ext = Optional.ofNullable(FilenameUtils.getExtension(file.getOriginalFilename())).orElse("")
  45. .toLowerCase().replace("jpeg", "jpg");
  46. if (path == null) {
  47. String basePath = Optional.ofNullable(file.getContentType()).orElse("application").split("/")[0];
  48. path = basePath + "/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
  49. + RandomStringUtils.randomAlphabetic(8)
  50. + "." + ext;
  51. }
  52. if (Pattern.matches("(jpg|png)", ext) && (compress || width != null || height != null)) {
  53. if (width == null && height == null) {
  54. width = Integer.MAX_VALUE;
  55. height = Integer.MAX_VALUE;
  56. } else if (height == null) {
  57. height = Integer.MAX_VALUE;
  58. } else if (width == null) {
  59. width = Integer.MAX_VALUE;
  60. }
  61. BufferedImage img = null;
  62. if ("jpg".equals(ext)) {
  63. img = ImageUtils.resizeJpg(file.getInputStream(), width, height, compress);
  64. } else if ("png".equals(ext)) {
  65. img = ImageUtils.resizePng(file.getInputStream(), width, height, compress);
  66. }
  67. Objects.requireNonNull(img, "图片压缩失败");
  68. ByteArrayOutputStream os = new ByteArrayOutputStream();
  69. ImageIO.write(img, ext, os);
  70. InputStream is = new ByteArrayInputStream(os.toByteArray());
  71. return storageService.uploadFromInputStream(is, path);
  72. }
  73. return storageService.uploadFromInputStream(file.getInputStream(), path);
  74. }
  75. @PostMapping("/base64")
  76. public String uploadImage(@RequestParam("base64") String base64,
  77. @RequestParam(value = "path", required = false) String path) {
  78. base64 = base64.substring(base64.indexOf(',') + 1);
  79. Base64.Decoder decoder = Base64.getDecoder();
  80. if (path == null) {
  81. String ext = ".jpg";
  82. try {
  83. InputStream is = new ByteArrayInputStream(decoder.decode(base64.getBytes()));
  84. String type = URLConnection.guessContentTypeFromStream(is);
  85. ext = type.replace("image/", ".").replace("jpeg", "jpg");
  86. } catch (Exception ignored) {
  87. }
  88. path = "image/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
  89. + RandomStringUtils.randomAlphabetic(8) + ext;
  90. }
  91. InputStream is;
  92. try {
  93. is = new ByteArrayInputStream(decoder.decode(base64.getBytes()));
  94. } catch (Exception e) {
  95. log.error("上传失败", e);
  96. throw new BusinessException("上传失败", e.getMessage());
  97. }
  98. return storageService.uploadFromInputStream(is, path);
  99. }
  100. @PostMapping("/fileObject")
  101. public FileObject uploadFileObject(@RequestParam("file") MultipartFile file,
  102. @RequestParam(value = "compress", defaultValue = "false") boolean compress,
  103. @RequestParam(value = "width", required = false) Integer width,
  104. @RequestParam(value = "height", required = false) Integer height) throws IOException {
  105. String ext = Optional.ofNullable(FilenameUtils.getExtension(file.getOriginalFilename())).orElse("")
  106. .toLowerCase().replace("jpeg", "jpg");
  107. String[] extList = new String[]{"jpg", "jpeg", "png", "gif", "mp4"};
  108. if (!ArrayUtils.contains(extList, ext.toLowerCase())) {
  109. throw new BusinessException("仅支持" + StringUtils.join(extList, "、") + "格式");
  110. }
  111. File tmpFile = File.createTempFile("upload_", "." + ext);
  112. FileUtils.copyToFile(file.getInputStream(), tmpFile);
  113. String path = "nft/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
  114. + RandomStringUtils.randomAlphabetic(8)
  115. + "." + ext;
  116. String url;
  117. if (Pattern.matches("(jpg|png)", ext) && (compress || width != null || height != null)) {
  118. if (width == null && height == null) {
  119. width = Integer.MAX_VALUE;
  120. height = Integer.MAX_VALUE;
  121. } else if (height == null) {
  122. height = Integer.MAX_VALUE;
  123. } else if (width == null) {
  124. width = Integer.MAX_VALUE;
  125. }
  126. BufferedImage img;
  127. if ("jpg".equals(ext)) {
  128. img = ImageUtils.resizeJpg(new FileInputStream(tmpFile), width, height, compress);
  129. } else {
  130. img = ImageUtils.resizePng(new FileInputStream(tmpFile), width, height, compress);
  131. }
  132. ByteArrayOutputStream os = new ByteArrayOutputStream();
  133. ImageIO.write(img, ext, os);
  134. InputStream is = new ByteArrayInputStream(os.toByteArray());
  135. url = storageService.uploadFromInputStream(is, path);
  136. } else {
  137. url = storageService.uploadFromInputStream(new FileInputStream(tmpFile), path);
  138. }
  139. String thumbUrl = null;
  140. if ("mp4".equalsIgnoreCase(ext)) {
  141. String thumbPath = "thumb_image/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
  142. + RandomStringUtils.randomAlphabetic(8) + ".jpg";
  143. FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(tmpFile);
  144. Java2DFrameConverter frameConverter = new Java2DFrameConverter();
  145. try {
  146. frameGrabber.start();
  147. Frame frame = null;
  148. while (frame == null) {
  149. frame = frameGrabber.grabKeyFrame();
  150. }
  151. Objects.requireNonNull(frame, "获取视频缩略图失败");
  152. BufferedImage thumbBi = frameConverter.convert(frame);
  153. BufferedImage thumbResized = ImageUtils.resizeJpg(thumbBi, 1000, 1000, false);
  154. ByteArrayOutputStream os = new ByteArrayOutputStream();
  155. ImageIO.write(thumbResized, "jpg", os);
  156. InputStream is = new ByteArrayInputStream(os.toByteArray());
  157. thumbUrl = storageService.uploadFromInputStream(is, thumbPath);
  158. } catch (Exception e) {
  159. e.printStackTrace();
  160. } finally {
  161. frameGrabber.stop();
  162. }
  163. }
  164. return new FileObject(file.getOriginalFilename(), url, thumbUrl, file.getContentType());
  165. }
  166. }