需求:使用Ajax返回图片数据展示在Img标签上
前端Ajax请求
<!--HTML标签-->
<img id="ImagePic" alt="Base64 encoded image" width="100" height="100" />
<script>
$.ajax({
type:'post',
data:{"param1":"0001","param2":"0002"}, //参数
dataType:'json',
url: "${root}/abc.do",
success: function(data) {
//将图片的Base64编码设置给src
$("#ImagePic").attr("src","data:image/png;base64,"+data);
},
error:function(data){
alert('响应失败!');
}
});
</script>
后端SpringMVC
@RequestMapping(value = "/abc")
@ResponseBody
public String ajaxFunction(String param1,String param2) throws Exception {
Image image = imageService.getBean(id);
//得到图片的二进制数据
byte[] imageData = image.getImageData();
//转换成JSON返回给前端
return JSON.toJSONString(imageData);
}
}