<%@ WebHandler Language="C#" Class="DownloadImage" %>
using System;
using System.Web;
using System.Web.Caching;
public class DownloadImage : IHttpHandler {
public void ProcessRequest (HttpContext context) {
HttpRequest req = context.Request;
HttpResponse resp = context.Response;
try
{
if (req.HttpMethod == "POST")
{
string header = "data:image/png;base64,";
string data = req.Form["data"];
//檢查上傳內容為PNG Data URI才處理
if (data.StartsWith(header))
{
//隨機產生GUID
string k = Guid.NewGuid().ToString();
//將Data URI轉成byte[]以GUID為Key存內Cache
HttpContext.Current.Cache.Add(k,
Convert.FromBase64String(data.Substring(header.Length)),
null, DateTime.Now.AddSeconds(60),
Cache.NoSlidingExpiration, CacheItemPriority.High, null);
//回傳GUID
resp.Write(k);
}
}
else if (req.HttpMethod == "GET")
{
string k = req.QueryString["k"];
//由前方傳入Key參數提取Cache中的資料
if (HttpContext.Current.Cache[k] != null)
{
//以檔案下載方式回傳byte[]內容
resp.AddHeader("content-disposition",
string.Format("attachment;filename={0:yyyyMMddHHmmss}.png", DateTime.Now));
resp.ContentType = "application/octet-stream";
resp.BinaryWrite((byte[])HttpContext.Current.Cache[k]);
//清除Cache中的內容
HttpContext.Current.Cache.Remove(k);
}
}
}
catch (Exception ex)
{
resp.ContentType = "text/plain";
resp.Write(ex.Message);
}
}
public bool IsReusable {
get {
return false;
}
}
}