FileUploadController.java 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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) throws IOException {
  117. String ext = Optional.ofNullable(FilenameUtils.getExtension(file.getOriginalFilename())).orElse("");
  118. String[] extList = new String[]{"jpg", "jpeg", "png", "gif", "mp4"};
  119. if (!ArrayUtils.contains(extList, ext.toLowerCase())) {
  120. throw new BusinessException("仅支持" + StringUtils.join(extList, "、") + "格式");
  121. }
  122. File tmpFile = File.createTempFile("upload_", "." + ext);
  123. FileUtils.copyToFile(file.getInputStream(), tmpFile);
  124. String path = "nft/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
  125. + RandomStringUtils.randomAlphabetic(8)
  126. + "." + ext;
  127. String url = storageService.uploadFromInputStream(new FileInputStream(tmpFile), path);
  128. String thumbUrl = null;
  129. if ("mp4".equalsIgnoreCase(ext)) {
  130. FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(tmpFile);
  131. frameGrabber.start();
  132. Java2DFrameConverter aa = new Java2DFrameConverter();
  133. try {
  134. BufferedImage bi;
  135. Frame f = frameGrabber.grabKeyFrame();
  136. bi = aa.convert(f);
  137. File thumbFile = null;
  138. while (bi != null) {
  139. thumbFile = File.createTempFile("video_thumb_", ".png");
  140. PngQuant pngQuant = new PngQuant();
  141. ImageIO.write(pngQuant.getRemapped(bi), "png", thumbFile);
  142. f = frameGrabber.grabKeyFrame();
  143. bi = aa.convert(f);
  144. }
  145. Objects.requireNonNull(thumbFile);
  146. String thumbPath = "thumb_image/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
  147. + RandomStringUtils.randomAlphabetic(8) + ".png";
  148. thumbUrl = storageService.uploadFromInputStream(new FileInputStream(thumbFile), thumbPath);
  149. } catch (Exception e) {
  150. e.printStackTrace();
  151. } finally {
  152. frameGrabber.stop();
  153. }
  154. }
  155. return new FileObject(file.getOriginalFilename(), url, thumbUrl, file.getContentType());
  156. }
  157. }