UploadUtils.java 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package com.steerinfo.dil.util;
  2. import com.google.common.io.Files;
  3. import com.steerinfo.dil.aspect.LogAspect;
  4. import com.steerinfo.framework.exception.BaseException;
  5. import com.steerinfo.framework.utils.io.FileUtils;
  6. import com.steerinfo.framework.utils.misc.IdGenerator;
  7. import org.apache.commons.lang3.StringUtils;
  8. import org.apache.log4j.Logger;
  9. import org.springframework.web.multipart.MultipartFile;
  10. import javax.imageio.ImageIO;
  11. import java.awt.image.BufferedImage;
  12. import java.io.ByteArrayOutputStream;
  13. import java.io.File;
  14. import java.io.FileNotFoundException;
  15. import java.io.IOException;
  16. /**
  17. * @author lyg
  18. * @Description:
  19. * @CreateTime 2022/7/15 19:05
  20. * @Version:1.0
  21. */
  22. public class UploadUtils {
  23. public static IdGenerator idGenerator = new IdGenerator(1,1);
  24. private static final Logger log = Logger.getLogger(UploadUtils.class);
  25. public UploadUtils() {
  26. }
  27. public static String uploadFile(MultipartFile file, String uploadPath, String imgPath) {
  28. String profilePhoto = null;
  29. if (file != null) {
  30. String fileId = idGenerator.getNextStr();
  31. String fileName = file.getOriginalFilename();
  32. String ext = Files.getFileExtension(fileName.toLowerCase());
  33. try {
  34. String filePath = uploadPath + imgPath + fileId + "." + ext;
  35. File newFile = new File(filePath);
  36. FileUtils.makesureParentDirExists(newFile);
  37. Files.write(file.getBytes(), newFile);
  38. } catch (IOException var10) {
  39. throw new BaseException("上传文件为空:" + var10.getMessage());
  40. }
  41. profilePhoto = uploadPath + imgPath + fileId + "." + ext;
  42. }
  43. return profilePhoto;
  44. }
  45. public static byte[] imageToByte(String imgUrl) {
  46. if (StringUtils.isEmpty(imgUrl)) {
  47. return null;
  48. } else {
  49. File file = new File(imgUrl);
  50. byte[] data = null;
  51. if (file.exists()) {
  52. String ext = Files.getFileExtension(imgUrl.toLowerCase());
  53. ByteArrayOutputStream out = new ByteArrayOutputStream();
  54. try {
  55. BufferedImage bi = ImageIO.read(file);
  56. ImageIO.write(bi, ext, out);
  57. data = out.toByteArray();
  58. } catch (FileNotFoundException var7) {
  59. var7.printStackTrace();
  60. } catch (IOException var8) {
  61. var8.printStackTrace();
  62. }
  63. }
  64. return data;
  65. }
  66. }
  67. }