第一步,读取blob数据,
第二步,将blob数据转换成byte数组
第三步,将byte数据进行base64加密转换成字符串并回传
第四步,接收字符串
第五步,将img控件的src设置成"data:image/jpeg;base64,"+接收的字符串;
相关代码:
java:
public String getAccountImg(String alias)
{
String sql = "SELECT imgrawdata FROM wx_account WHERE alias = ?";
PreparedStatement ps = DBUtils.createPreparedStatement(DBUtils.connection, sql);
DBUtils.setString(ps, 1, alias);
ResultSet res = DBUtils.executeQuery(ps);
DBUtils.next(res);
Blob imagerawdata = DBUtils.getBlob(res, "imgrawdata");
byte[] b = blobToBytes(imagerawdata);
return Base64.encode(b);
}
private byte[] blobToBytes(Blob blob) {
BufferedInputStream is = null;
try {
is = new BufferedInputStream(blob.getBinaryStream());
byte[] bytes = new byte[(int) blob.length()];
int len = bytes.length;
int offset = 0;
int read = 0;
while (offset < len && (read = is.read(bytes, offset, len - offset)) >= 0) {
offset += read;
}
return bytes;
} catch (Exception e) {
return null;
} finally {
try {
is.close();
is = null;
} catch (IOException e) {
return null;
}
}
}
~~~~~~~~~~~~~~
js:
var img= xmlhttp.responseText;
alert(img);
document.getElementById("image").src = "data:image/jpeg;base64,"+img;
mysql中以blob形式存储的图片文件 通过ajax方式传输 在js中设置成img控件的src,布布扣,bubuko.com