Base64编码图片存取与前台显示

需求:将Base64编码图片以BLOB类型存入数据库,需要时取出显示

后台:

String base64str=new String(log.getRequest_imgdata());//log为实体 括号里面是图像的get方法 返回为Byte[]型
String new str=new String(""data:image/jpg;base64,"+base64str+""");//拼装Base64字符串头
response.getWriter().write(newstr);//将完整Base64字符串返回前台

前台Js:

var srcUrl = appJP.urlReqImg +"?log_id="+row.log_id;//请求URL
        $.get(srcUrl,function(data){
            var imgWindow = $("#imgDetail").html("<img src="+data+">");//接收Base64字符串,并转换为图片显示
            $("#showImg").window({title:"图片详情","auto"}).window("open").window("center");
        })

以上已实现从数据库取出BLOB类型Base64图像数据(Java中为byte[])转换为字符串,并发送至前台显示

但是在测试中发现稍微大一点的图像(几百KB)在部分IE浏览器中不能显示,查询资料发现是IE8以下对Base64解码长度限制的问题

解决方案:更换后台到前台传输图像数据形式为流的形式

后台:  

String base64str=new String(log.getRequest_imgdata());
BASE64Decoder decoder=new BASE64Decoder();
byte[] imgbyte=decoder.decodeBuffer(base64str);//解码Base64图片数据
response.setContentType("image/jpeg");
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(imgbyte);
outputStream.flush();

前台js:

var srcUrl = appJP.urlReqImg +"?log_id="+row.log_id;
var imgWindow = $("#imgDetail").html("<img src="+srcUrl+">");
$("#showImg").window({title:"图片详情","auto"}).window("open").window("center");
原文地址:https://www.cnblogs.com/vayci/p/5439991.html