package com.ruoyi.web.controller.wx; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.system.domain.AttachMngs; import com.ruoyi.system.service.IAttachMngsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.util.Map; @RestController @RequestMapping("/attachmngs") public class AttachmngsController { @Autowired private IAttachMngsService attachMngsService; /** * 上传图片 * * @param file 图片 * @return * @throws Exception */ @PostMapping public AjaxResult updateAttachmngs(@RequestParam("avatarfile") MultipartFile file, @RequestParam("attachId") Long attachId, HttpServletRequest request) throws Exception { if (file.isEmpty()) { return AjaxResult.error("上传失败请重试1"); } byte[] bytes = file.getBytes(); AttachMngs attachMngs = new AttachMngs(); attachMngs.setSysId(1L); attachMngs.setAttachId(attachId); attachMngs.setAttachFile(toObjects(bytes)); Integer i = attachMngsService.insertAttachMngs(attachMngs); if (i != 1) { return AjaxResult.error("上传失败请重试2"); } // 拼接url String serverName = request.getServerName(); int serverPort = request.getServerPort(); return AjaxResult.success("操作成功", "http://" + serverName + ":" + serverPort + "/attachmngs/img/" + attachId); } /** * 获取图片 * * @param attachId * @return */ @GetMapping(value = "/img/{attachId}", produces = MediaType.IMAGE_JPEG_VALUE) public byte[] getImg(@PathVariable("attachId") String attachId) { Byte[] img = attachMngsService.getImg(attachId); return toPrimitives(img); } // byte[] to Byte[] private Byte[] toObjects(byte[] bytesPrim) { Byte[] bytes = new Byte[bytesPrim.length]; int i = 0; for (byte b : bytesPrim) bytes[i++] = b; // Autoboxing return bytes; } private byte[] toPrimitives(Byte[] oBytes) { byte[] bytes = new byte[oBytes.length]; for(int i = 0; i < oBytes.length; i++) { bytes[i] = oBytes[i]; } return bytes; } }