1.工具类
package com.atguigu.yygh.common.util; import org.apache.commons.codec.binary.Base64; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; public class ImageBase64Util { public static void main(String[] args) { String imageFile= "G:\0722test\111.png";// 待处理的图片 System.out.println(getImageString(imageFile)); } public static String getImageString(String imageFile){ InputStream is = null; try { byte[] data = null; is = new FileInputStream(new File(imageFile)); data = new byte[is.available()]; is.read(data); return new String(Base64.encodeBase64(data)); } catch (Exception e) { e.printStackTrace(); } finally { if (null != is) { try { is.close(); is = null; } catch (Exception e) { e.printStackTrace(); } } } return ""; } }
测试
<img src="data:image/png;base64,iVBORw0..>,改文件名后缀
4.接口
@ApiOperation(value = "上传医院") @PostMapping("saveHospital") public Result saveHospital(HttpServletRequest request) throws IOException { JSONObject json= HttpRequestPost.getRequestJsonObject(request); Map<String, Object> params = JSONObject.parseObject(json.toJSONString(), new TypeReference<Map<String, Object>>(){}); //必须参数校验 略 String hoscode = (String)params.get("hoscode"); if(StringUtils.isEmpty(hoscode)) { throw new YyghException(ResultCodeEnum.PARAM_ERROR); } //传输过程中“+”转换为了“ ”,因此我们要转换回来 String logoDataString = (String)params.get("logoData"); if(!StringUtils.isEmpty(logoDataString)) { String logoData = logoDataString.replaceAll("", "+"); params.put("logoData", logoData); } //签名校验 if(!HttpRequestHelper.isSignEquals(params, hospitalSetService.getSignKey(hoscode))) { throw new YyghException(ResultCodeEnum.SIGN_ERROR); } // Map<String, Object> paramMap = HttpRequestHelper.switchMap(request.getParameterMap()); hospitalService.save(params); return Result.ok(); }