FileUploadController.java 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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 lombok.extern.slf4j.Slf4j;
  6. import org.apache.commons.io.FileUtils;
  7. import org.apache.commons.io.FilenameUtils;
  8. import org.apache.commons.lang3.ArrayUtils;
  9. import org.apache.commons.lang3.RandomStringUtils;
  10. import org.apache.commons.lang3.StringUtils;
  11. import org.bytedeco.javacv.FFmpegFrameGrabber;
  12. import org.bytedeco.javacv.Frame;
  13. import org.bytedeco.javacv.Java2DFrameConverter;
  14. import org.pngquant.PngQuant;
  15. import org.springframework.beans.factory.annotation.Autowired;
  16. import org.springframework.web.bind.annotation.PostMapping;
  17. import org.springframework.web.bind.annotation.RequestMapping;
  18. import org.springframework.web.bind.annotation.RequestParam;
  19. import org.springframework.web.bind.annotation.RestController;
  20. import org.springframework.web.multipart.MultipartFile;
  21. import javax.imageio.ImageIO;
  22. import java.awt.image.BufferedImage;
  23. import java.io.*;
  24. import java.net.URLConnection;
  25. import java.text.SimpleDateFormat;
  26. import java.util.Base64;
  27. import java.util.Date;
  28. import java.util.Objects;
  29. import java.util.Optional;
  30. import java.util.regex.Pattern;
  31. @RestController
  32. @RequestMapping("/upload")
  33. @Slf4j
  34. public class FileUploadController {
  35. @Autowired
  36. private StorageService storageService;
  37. @PostMapping("/file")
  38. public String uploadFile(@RequestParam("file") MultipartFile file,
  39. @RequestParam(value = "path", required = false) String path,
  40. @RequestParam(value = "compress", defaultValue = "false") boolean compress,
  41. @RequestParam(value = "width", required = false) Integer width,
  42. @RequestParam(value = "height", required = false) Integer height) throws IOException {
  43. if (width != null && height == null) {
  44. height = Integer.MAX_VALUE;
  45. }
  46. if (height != null && width == null) {
  47. width = Integer.MAX_VALUE;
  48. }
  49. String ext = Optional.ofNullable(FilenameUtils.getExtension(file.getOriginalFilename())).orElse("")
  50. .toLowerCase().replace("jpeg", "jpg");
  51. if (Pattern.matches("(jpg|png)", ext)) {
  52. File tmpFile = null;
  53. try {
  54. tmpFile = File.createTempFile("upload", "." + ext);
  55. FileUtils.copyToFile(file.getInputStream(), tmpFile);
  56. } catch (IOException e) {
  57. e.printStackTrace();
  58. throw new BusinessException("上传失败");
  59. }
  60. PngQuant pngQuant = new PngQuant();
  61. ImageIO.write(pngQuant.getRemapped(ImageIO.read(file.getInputStream())),
  62. "png", new File("/Users/drew/Downloads/111.png"));
  63. }
  64. if (path == null) {
  65. String basePath = "application";
  66. try {
  67. basePath = file.getContentType().split("/")[0];
  68. } catch (Exception ignored) {
  69. }
  70. path = basePath + "/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
  71. + RandomStringUtils.randomAlphabetic(8)
  72. + "." + FilenameUtils.getExtension(file.getOriginalFilename());
  73. }
  74. InputStream is;
  75. try {
  76. is = file.getInputStream();
  77. } catch (IOException e) {
  78. log.error("上传失败", e);
  79. throw new BusinessException("上传失败", e.getMessage());
  80. }
  81. return storageService.uploadFromInputStream(is, path);
  82. }
  83. @PostMapping("/base64")
  84. public String uploadImage(@RequestParam("base64") String base64,
  85. @RequestParam(value = "path", required = false) String path) {
  86. base64 = base64.substring(base64.indexOf(',') + 1);
  87. Base64.Decoder decoder = Base64.getDecoder();
  88. if (path == null) {
  89. String ext = ".jpg";
  90. try {
  91. InputStream is = new ByteArrayInputStream(decoder.decode(base64.getBytes()));
  92. String type = URLConnection.guessContentTypeFromStream(is);
  93. ext = type.replace("image/", ".").replace("jpeg", "jpg");
  94. } catch (Exception ignored) {
  95. }
  96. path = "image/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
  97. + RandomStringUtils.randomAlphabetic(8) + ext;
  98. }
  99. InputStream is;
  100. try {
  101. is = new ByteArrayInputStream(decoder.decode(base64.getBytes()));
  102. } catch (Exception e) {
  103. log.error("上传失败", e);
  104. throw new BusinessException("上传失败", e.getMessage());
  105. }
  106. return storageService.uploadFromInputStream(is, path);
  107. }
  108. @PostMapping("/fileObject")
  109. public FileObject uploadFileObject(@RequestParam("file") MultipartFile file) throws IOException {
  110. String ext = Optional.ofNullable(FilenameUtils.getExtension(file.getOriginalFilename())).orElse("");
  111. String[] extList = new String[]{"jpg", "jpeg", "png", "gif", "mp4"};
  112. if (!ArrayUtils.contains(extList, ext.toLowerCase())) {
  113. throw new BusinessException("仅支持" + StringUtils.join(extList, "、") + "格式");
  114. }
  115. File tmpFile = File.createTempFile("upload_", "." + ext);
  116. FileUtils.copyToFile(file.getInputStream(), tmpFile);
  117. String path = "nft/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
  118. + RandomStringUtils.randomAlphabetic(8)
  119. + "." + ext;
  120. String url = storageService.uploadFromInputStream(new FileInputStream(tmpFile), path);
  121. String thumbUrl = null;
  122. if ("mp4".equalsIgnoreCase(ext)) {
  123. FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(tmpFile);
  124. frameGrabber.start();
  125. Java2DFrameConverter aa = new Java2DFrameConverter();
  126. try {
  127. BufferedImage bi;
  128. Frame f = frameGrabber.grabKeyFrame();
  129. bi = aa.convert(f);
  130. File thumbFile = null;
  131. while (bi != null) {
  132. thumbFile = File.createTempFile("video_thumb_", ".png");
  133. PngQuant pngQuant = new PngQuant();
  134. ImageIO.write(pngQuant.getRemapped(bi), "png", thumbFile);
  135. f = frameGrabber.grabKeyFrame();
  136. bi = aa.convert(f);
  137. }
  138. Objects.requireNonNull(thumbFile);
  139. String thumbPath = "thumb_image/" + new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
  140. + RandomStringUtils.randomAlphabetic(8) + ".png";
  141. thumbUrl = storageService.uploadFromInputStream(new FileInputStream(thumbFile), thumbPath);
  142. } catch (Exception e) {
  143. e.printStackTrace();
  144. } finally {
  145. frameGrabber.stop();
  146. }
  147. }
  148. return new FileObject(file.getOriginalFilename(), url, thumbUrl, file.getContentType());
  149. }
  150. }