码迷,mamicode.com
首页 > 数据库 > 详细

mysql中以blob形式存储的图片文件 通过ajax方式传输 在js中设置成img控件的src

时间:2014-08-14 16:11:48      阅读:551      评论:0      收藏:0      [点我收藏+]

标签:http   java   os   io   文件   数据   ar   cti   

第一步,读取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

mysql中以blob形式存储的图片文件 通过ajax方式传输 在js中设置成img控件的src

标签:http   java   os   io   文件   数据   ar   cti   

原文地址:http://www.cnblogs.com/miazz/p/3912542.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!