根据生成的Echart图表获取图表相关信息,chart.getDataURL(),并将相关信息传递给服务器,服务器根据传递的信息生成对应的图片到指定位置
前端代码
//图表实例
var chart= ec.init($(".chart")[0]);
/**
* 导出文件类型 -html excel pdf
* @param type
*/
function exportFile(type){
// 向后台发起请求保存图片到指定目录.
var param={
"downType":type,
"picInfo": chart.getDataURL()
}
$.ajax({
type:'post',
url: ctx+"/*****/saveImage.do?"+csrfName+"="+csrfValue,
data: param,
success: function(msg) {
console.log(msg)
if(msg != "error"){
console.log("the file is exit----------------")
}else{//文件保存成图片失败
console.log("the file is not exit----------------")
}
},
error:function(){
}
});
}
后端代码:
/**
* Echart图片生成
* @return
* @throws IOException
*/
@RequestMapping(value = "/******/saveImage.do", method = RequestMethod.POST)
public void saveEchartImage(HttpServletRequest request, HttpServletResponse response) throws IOException{
String picInfo=request.getParameter("picInfo");
UUID uuid = UUID.randomUUID();
String name=uuid.toString();
String downloadtype=request.getParameter("downType");
if (StringUtils.isBlank(picInfo)) {
log.debug("picInfo为空,未从前台获取到base64图片信息!");
response.getWriter().write("error");
}else{
File currpath = new File(getClass().getClassLoader().getResource("").getPath());
//获取服务器根路径
File parentPath = new File(currpath.getParent());
String pppath = parentPath.getParent();
String imgFolder=pppath+ "/imgfile/";
String imgPath = imgFolder+name+".png" ;//图片存储路径
log.debug("saveEchartImage img is:"+imgPath);
// 传递过程中 "+" 变为了 " ".
String newPicInfo = picInfo.replaceAll(" ", "+");
decodeBase64(newPicInfo, new File(imgPath));
//log.warn("从echarts中生成图片的的路径为:{}", picPath);
response.getWriter().write(name);
}
}
/**
* 解析Base64位信息并输出到某个目录下面.
* @param base64Info base64串
* @param picPath 生成的文件路径
* @return 文件地址
*/
private File decodeBase64(String base64Info, File picPath) {
if (StringUtils.isEmpty(base64Info)) {
return null;
}
// 数据中:data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABI4AAAEsCAYAAAClh/jbAAA ... 在"base64,"之后的才是图片信息
String[] arr = base64Info.split("base64,");
// 将图片输出到系统某目录.
OutputStream out = null;
try {
// 使用了Apache commons codec的包来解析Base64
byte[] buffer = Base64.decodeBase64(arr[1]);
out = new FileOutputStream(picPath);
out.write(buffer);
} catch (IOException e) {
//e.printStackTrace();
log.error("解析Base64图片信息并保存到某目录下出错!", e);
} finally {
IOUtils.closeQuietly(out);
}
return picPath;
}
可以在指定路径查看生成的图片