AttachmngsController.java 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. // String fileName = file.getOriginalFilename();
  40. // String suffixName = fileName.substring(fileName.lastIndexOf("."));
  41. // 拼接url
  42. String serverName = request.getServerName();
  43. int serverPort = request.getServerPort();
  44. return AjaxResult.success("操作成功", "http://" + serverName + ":" + serverPort + "/attachmngs/img/" + attachId);
  45. }
  46. /**
  47. * 获取图片
  48. *
  49. * @param attachId
  50. * @return
  51. */
  52. @GetMapping(value = "/img/{attachId}", produces = MediaType.IMAGE_JPEG_VALUE)
  53. public byte[] getImg(@PathVariable("attachId") String attachId) {
  54. Byte[] img = attachMngsService.getImg(attachId);
  55. return toPrimitives(img);
  56. }
  57. // byte[] to Byte[]
  58. private Byte[] toObjects(byte[] bytesPrim) {
  59. Byte[] bytes = new Byte[bytesPrim.length];
  60. int i = 0;
  61. for (byte b : bytesPrim) bytes[i++] = b; // Autoboxing
  62. return bytes;
  63. }
  64. private byte[] toPrimitives(Byte[] oBytes) {
  65. byte[] bytes = new byte[oBytes.length];
  66. for (int i = 0; i < oBytes.length; i++) {
  67. bytes[i] = oBytes[i];
  68. }
  69. return bytes;
  70. }
  71. }