public partial class WebForm : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { } } protected void btnDownLoad_Click(object sender, EventArgs e) { try { if (!string.IsNullOrWhiteSpace(hidImageUrl.Value)) { Response.Buffer = true; Response.AddHeader("Accept-Language", "zh-tw"); string content = hidImageUrl.Value; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(content); req.Timeout = 10000; HttpWebResponse rep = (HttpWebResponse)req.GetResponse(); Stream s = rep.GetResponseStream(); hidImageUrl.Value = ""; Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpeg", System.Text.Encoding.UTF8));//attachment Response.ContentType = "image/jpeg;charset=gbk"; System.Drawing.Image img = System.Drawing.Image.FromStream(s); img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); s.Close(); rep.Close(); Response.End(); } } catch (Exception ex) { Response.Write("请联系管理员!" + ex.ToString()); } } }}
function downloadFile(fileName, content) { $('#ContentPlaceHolder1_hidImageUrl').val(content); $('#ContentPlaceHolder1_btnDownLoad').click(); return false;}
以上代码主要是通过JS代码调用服务器控件的OnClick事件;在后台把图片下载后保存至Response流中;实现类似下载Excel文件的功能