代码笔记 | Echart显示或导出图片

接收Echar生成的Base64数据,转换为图片或生成下载。

 
<%@ WebHandler Language="C#" Class="ExportImg" %>

using System;
using System.Web;
using System.Data;

public class ExportImg : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        try
        {
            string req = context.Request["imgdata"].ToString();
            base64TOpic(context, req);
        }
        catch
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write("参数错误,请生成图片后再导出!!");
        }
    }


    public void base64TOpic(HttpContext context, string req)
    {
        String[] url = req.Split(',');
        String u = url[1];
        byte[] buffer = Convert.FromBase64String(u);
        System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer);
        //输出为文件下载
        context.Response.ContentType = "application/octet-steam";
        context.Response.AddHeader("Content-Disposition", "attachment;   filename=" + HttpUtility.UrlEncode("导出图片.png", System.Text.Encoding.UTF8));
        //输出为文件下载

        //输出为图片
        //context.Response.ContentType = "image/png";
        //输出为图片


        //二进制流一次性输出
        //context.Response.BinaryWrite(buffer);
        //二进制流一次性输出

        //二进制流分片输出
        context.Response.Cache.SetCacheability(HttpCacheability.Public);
        context.Response.BufferOutput = false;
        const int buffersize = 1024 * 16;
        byte[] Buffer = new byte[buffersize];
        int count = ms.Read(Buffer, 0, buffersize);
        while (count > 0)
        {
            context.Response.OutputStream.Write(Buffer, 0, count);
            count = ms.Read(Buffer, 0, buffersize);
        }
        //二进制流分片输出

        context.Response.Flush();
        context.Response.End();
    }


    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}


你可能感兴趣的:(代码笔记)