后台代码:
public String getBase64(SysFile sysFile){ String imgStr = ""; try { File file = new File("C:\EThinkTankFile\20180402160120431.jpg"); FileInputStream fis = new FileInputStream(file); byte[] buffer = new byte[(int) file.length()]; int offset = 0; int numRead = 0; while (offset < buffer.length && (numRead = fis.read(buffer, offset, buffer.length - offset)) >= 0) { offset += numRead; } if (offset != buffer.length) { throw new IOException("Could not completely read file " + file.getName()); } fis.close(); BASE64Encoder encoder = new BASE64Encoder(); imgStr = encoder.encode(buffer); } catch (Exception e) { e.printStackTrace(); } return "data:image/jpeg;base64,"+imgStr; }
前台代码:<img id="picture" width="690" height="460" src="">
通过ajax 请求将后台返回的字符串 添加到src属性中去 $("#picture").attr("src","后台返回的base64字符串");