js下載圖片(不讓瀏覽器開啟)
阿新 • • 發佈:2019-02-04
<a href="Handler1.ashx" download="123.jpeg">下載而不是開啟</a>
前端a標籤
public void ProcessRequest(HttpContext context) { Bitmap img = GetBitmap("http://伺服器圖片url.jpeg"); MemoryStream ms = new MemoryStream(); img.Save(ms, ImageFormat.Jpeg); context.Response.ClearContent(); context.Response.ContentType = "Image/Jpeg"; context.Response.BinaryWrite(ms.ToArray()); } public Bitmap GetBitmap(string url) { if (String.IsNullOrEmpty(url)) return null; else { try { url = url.Replace(" ", "%20"); url = url.Replace("&", "&"); } catch { } } Bitmap bitmap = null; HttpWebRequest myRequest = null; HttpWebResponse myResponse = null; Stream responseStream = null; try { myRequest = (HttpWebRequest)WebRequest.Create(url); myRequest.Timeout = 15 * 1000; myRequest.CookieContainer = new CookieContainer(); myResponse = (HttpWebResponse)myRequest.GetResponse(); responseStream = myResponse.GetResponseStream(); Image image = Image.FromStream(responseStream); bitmap = new Bitmap(image); } catch { } finally { if (myResponse != null) { myResponse.Close(); } if (responseStream != null) { responseStream.Close(); } if (myRequest != null) { myRequest.Abort(); } } return bitmap; }
處理程式