AttachmngsController.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package com.ruoyi.web.controller.wx;
  2. import com.ruoyi.common.core.domain.AjaxResult;
  3. import com.ruoyi.system.domain.AttachMngs;
  4. import com.ruoyi.system.service.IAttachMngsService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.http.MediaType;
  7. import org.springframework.web.bind.annotation.*;
  8. import org.springframework.web.multipart.MultipartFile;
  9. import javax.servlet.http.HttpServletRequest;
  10. import java.util.Map;
  11. @RestController
  12. @RequestMapping("/attachmngs")
  13. public class AttachmngsController {
  14. @Autowired
  15. private IAttachMngsService attachMngsService;
  16. /**
  17. * 上传图片
  18. *
  19. * @param file 图片
  20. * @return
  21. * @throws Exception
  22. */
  23. @PostMapping
  24. public AjaxResult updateAttachmngs(@RequestParam("avatarfile") MultipartFile file,
  25. @RequestParam("attachId") Long attachId,
  26. HttpServletRequest request) throws Exception {
  27. if (file.isEmpty()) {
  28. return AjaxResult.error("上传失败请重试1");
  29. }
  30. byte[] bytes = file.getBytes();
  31. AttachMngs attachMngs = new AttachMngs();
  32. attachMngs.setSysId(1L);
  33. attachMngs.setAttachId(attachId);
  34. attachMngs.setAttachFile(toObjects(bytes));
  35. Integer i = attachMngsService.insertAttachMngs(attachMngs);
  36. if (i != 1) {
  37. return AjaxResult.error("上传失败请重试2");
  38. }
  39. // 拼接url
  40. String serverName = request.getServerName();
  41. int serverPort = request.getServerPort();
  42. return AjaxResult.success("操作成功", "http://" + serverName + ":" + serverPort + "/attachmngs/img/" + attachId);
  43. }
  44. /**
  45. * 获取图片
  46. *
  47. * @param attachId
  48. * @return
  49. */
  50. @GetMapping(value = "/img/{attachId}", produces = MediaType.IMAGE_JPEG_VALUE)
  51. public byte[] getImg(@PathVariable("attachId") String attachId) {
  52. Byte[] img = attachMngsService.getImg(attachId);
  53. return toPrimitives(img);
  54. }
  55. // byte[] to Byte[]
  56. private Byte[] toObjects(byte[] bytesPrim) {
  57. Byte[] bytes = new Byte[bytesPrim.length];
  58. int i = 0;
  59. for (byte b : bytesPrim) bytes[i++] = b; // Autoboxing
  60. return bytes;
  61. }
  62. private byte[] toPrimitives(Byte[] oBytes)
  63. {
  64. byte[] bytes = new byte[oBytes.length];
  65. for(int i = 0; i < oBytes.length; i++) {
  66. bytes[i] = oBytes[i];
  67. }
  68. return bytes;
  69. }
  70. }