FileUploadController.java 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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) {
  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);
  64. } else if ("png".equals(ext)) {
  65. img = ImageUtils.resizePng(file.getInputStream(), width, height, true);
  66. }
  67. ByteArrayOutputStream os = new ByteArrayOutputStream();
  68. ImageIO.write(img, ext, os);
  69. InputStream is = new ByteArrayInputStream(os.toByteArray());
  70. return storageService.uploadFromInputStream(is, path);
  71. } else if (width != null || height != null) {
  72. if (height == null) {
  73. height = Integer.MAX_VALUE;
  74. } else if (width == null) {
  75. width = Integer.MAX_VALUE;
  76. }
  77. BufferedImage img = null;
  78. if ("jpg".equals(ext)) {
  79. img = ImageUtils.resizeJpg(file.getInputStream(), width, height);
  80. } else if ("png".equals(ext)) {
  81. img = ImageUtils.resizePng(file.getInputStream(), width, height, false);
  82. }
  83. ByteArrayOutputStream os = new ByteArrayOutputStream();
  84. ImageIO.write(img, ext, os);
  85. InputStream is = new ByteArrayInputStream(os.toByteArray());
  86. return storageService.uploadFromInputStream(is, path);
  87. }
  88. return storageService.uploadFromInputStream(file.getInputStream(), path);
  89. }
  90. @PostMapping("/base64")
  91. public String uploadImage(@RequestParam("base64") String base64,
  92. @RequestParam(value = "path", required = false) String path) {
  93. base64 = base64.substring(base64.indexOf(',') + 1);
  94. Base64.Decoder decoder = Base64.getDecoder();
  95. if (path == null) {
  96. String ext = ".jpg";
  97. try {
  98. InputStream is = new ByteArrayInputStream(decoder.decode(base64.getBytes()));
  99. String type = URLConnection.guessContentTypeFromStream(is);
  100. ext = type.replace("image/", ".").replace("jpeg", "jpg");
  101. } catch (Exception ignored) {
  102. }
  103. path = "image/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
  104. + RandomStringUtils.randomAlphabetic(8) + ext;
  105. }
  106. InputStream is;
  107. try {
  108. is = new ByteArrayInputStream(decoder.decode(base64.getBytes()));
  109. } catch (Exception e) {
  110. log.error("上传失败", e);
  111. throw new BusinessException("上传失败", e.getMessage());
  112. }
  113. return storageService.uploadFromInputStream(is, path);
  114. }
  115. @PostMapping("/fileObject")
  116. public FileObject uploadFileObject(@RequestParam("file") MultipartFile file,
  117. @RequestParam(value = "compress", defaultValue = "false") boolean compress,
  118. @RequestParam(value = "width", required = false) Integer width,
  119. @RequestParam(value = "height", required = false) Integer height) throws IOException {
  120. String ext = Optional.ofNullable(FilenameUtils.getExtension(file.getOriginalFilename())).orElse("")
  121. .toLowerCase().replace("jpeg", "jpg");
  122. String[] extList = new String[]{"jpg", "jpeg", "png", "gif", "mp4"};
  123. if (!ArrayUtils.contains(extList, ext.toLowerCase())) {
  124. throw new BusinessException("仅支持" + StringUtils.join(extList, "、") + "格式");
  125. }
  126. File tmpFile = File.createTempFile("upload_", "." + ext);
  127. FileUtils.copyToFile(file.getInputStream(), tmpFile);
  128. String path = "nft/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
  129. + RandomStringUtils.randomAlphabetic(8)
  130. + "." + ext;
  131. String url;
  132. if (Pattern.matches("(jpg|png)", ext) && compress) {
  133. if (width == null && height == null) {
  134. width = Integer.MAX_VALUE;
  135. height = Integer.MAX_VALUE;
  136. } else if (height == null) {
  137. height = Integer.MAX_VALUE;
  138. } else if (width == null) {
  139. width = Integer.MAX_VALUE;
  140. }
  141. BufferedImage img = null;
  142. if ("jpg".equals(ext)) {
  143. img = ImageUtils.resizeJpg(new FileInputStream(tmpFile), width, height);
  144. } else {
  145. img = ImageUtils.resizePng(new FileInputStream(tmpFile), width, height, true);
  146. }
  147. ByteArrayOutputStream os = new ByteArrayOutputStream();
  148. ImageIO.write(img, ext, os);
  149. InputStream is = new ByteArrayInputStream(os.toByteArray());
  150. url = storageService.uploadFromInputStream(is, path);
  151. } else if (Pattern.matches("(jpg|png)", ext) && (width != null || height != null)) {
  152. if (height == null) {
  153. height = Integer.MAX_VALUE;
  154. } else if (width == null) {
  155. width = Integer.MAX_VALUE;
  156. }
  157. BufferedImage img = null;
  158. if ("jpg".equals(ext)) {
  159. img = ImageUtils.resizeJpg(new FileInputStream(tmpFile), width, height);
  160. } else {
  161. img = ImageUtils.resizePng(new FileInputStream(tmpFile), width, height, false);
  162. }
  163. ByteArrayOutputStream os = new ByteArrayOutputStream();
  164. ImageIO.write(img, ext, os);
  165. InputStream is = new ByteArrayInputStream(os.toByteArray());
  166. url = storageService.uploadFromInputStream(is, path);
  167. } else {
  168. url = storageService.uploadFromInputStream(new FileInputStream(tmpFile), path);
  169. }
  170. String thumbUrl = null;
  171. if ("mp4".equalsIgnoreCase(ext)) {
  172. FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(tmpFile);
  173. frameGrabber.start();
  174. Java2DFrameConverter aa = new Java2DFrameConverter();
  175. try {
  176. BufferedImage bi;
  177. Frame f = frameGrabber.grabKeyFrame();
  178. bi = aa.convert(f);
  179. File thumbFile = null;
  180. while (bi != null) {
  181. thumbFile = File.createTempFile("video_thumb_", ".png");
  182. PngQuant pngQuant = new PngQuant();
  183. ImageIO.write(pngQuant.getRemapped(bi), "png", thumbFile);
  184. f = frameGrabber.grabKeyFrame();
  185. bi = aa.convert(f);
  186. }
  187. Objects.requireNonNull(thumbFile);
  188. String thumbPath = "thumb_image/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
  189. + RandomStringUtils.randomAlphabetic(8) + ".png";
  190. thumbUrl = storageService.uploadFromInputStream(new FileInputStream(thumbFile), thumbPath);
  191. } catch (Exception e) {
  192. e.printStackTrace();
  193. } finally {
  194. frameGrabber.stop();
  195. }
  196. }
  197. return new FileObject(file.getOriginalFilename(), url, thumbUrl, file.getContentType());
  198. }
  199. }