整体思路:
1、前端:把echart的base64传递到后端
2、后端:在后台进行base64解码,生成指定路径下的图片
前端,伪代码:
….
myCharts1.setOption(option1);
setTimeout(exportImage, 2000);//切记:一定设置这个延迟,否则生成的图片是黑色的。
function exportImage(){
var picBase64Info = myCharts1.getDataURL();//获取图片的base64传递后台,生成图片,供导出报表使用
var data = “a=”+encodeURIComponent(myCharts1.getDataURL(“png”));
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”);
}
xmlhttp.open(“POST”,”/web/model/login/savetp.do”,true);
xmlhttp.setRequestHeader(“Content-type”,”application/x-www-form-urlencoded”);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//alert(“保存成功”);
}
}
xmlhttp.send(data);
}
后端,伪代码:
/**
* 保存图片
* @param request
* @return
*/
@RequestMapping(value = “/savetp”, method = RequestMethod.POST)
public void saveImage(HttpServletRequest request) throws Exception{
String a = request.getParameter(“a”);
String[] url = a.split(“,”);
String u = url[1];
byte[] b = new BASE64Decoder().decodeBuffer(u);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
// 生成png图片
String imgpath=request.getRealPath(“/”)+”/export/fw.png”;
OutputStream out = new FileOutputStream(imgpath);
out.write(b);
out.flush();
out.close();
}