ImageController.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package com.hichina.admin.hichinaadminbackend.controller;
  2. import com.aliyun.oss.OSSClient;
  3. import com.hichina.admin.hichinaadminbackend.model.DTO.HichinaResponse;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.core.env.Environment;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RequestMethod;
  10. import org.springframework.web.bind.annotation.RequestParam;
  11. import org.springframework.web.bind.annotation.RestController;
  12. import org.springframework.web.multipart.MultipartFile;
  13. import java.io.ByteArrayInputStream;
  14. import java.io.IOException;
  15. @RestController
  16. @RequestMapping("/api/v1/image")
  17. public class ImageController {
  18. private static final Logger LOG = LoggerFactory.getLogger(ImageController.class);
  19. @Autowired
  20. private Environment env;
  21. @RequestMapping(value = "/upload", method = RequestMethod.POST)
  22. public HichinaResponse uploadProfile(@RequestParam("imageFile") MultipartFile uploadFile, @RequestParam("expectedType") String expectedType) {
  23. HichinaResponse ret = new HichinaResponse();
  24. try {
  25. byte[] profileBytes = uploadFile.getBytes();
  26. String BLOG_BUCKET_NAME = env.getProperty("aliyun.blog.bucket");
  27. String endpoint = env.getProperty("aliyun.oss.endpoint");
  28. String ossDomain = env.getProperty("aliyun.oss.endpoint.domain");
  29. String accessKeyId = env.getProperty("hichina.root.access.key.id");
  30. String accessKeySecret = env.getProperty("hichina.root.access.key.secret");
  31. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  32. String key = java.util.UUID.randomUUID().toString() + ".jpg";
  33. ossClient.putObject(BLOG_BUCKET_NAME, key, new ByteArrayInputStream(profileBytes));
  34. ossClient.shutdown();
  35. ret.setOk(true);
  36. String style = expectedType.equals("blogImage") ? "blogcontent" : "thumbnail";
  37. String url = "https://" + BLOG_BUCKET_NAME + "." + ossDomain + "/" + key + "?x-oss-process=style/" + style;
  38. ret.setData(url);
  39. return ret;
  40. } catch (IOException e) {
  41. LOG.error("==============" + e.getMessage() + "========");
  42. return null;
  43. }
  44. }
  45. }