js 下载图片与下载文件的方式一样;保存至本地 ASP.NET 方式
<asp:Button ID="btnDownLoad" runat="server" style="display: none" Text="a" OnClick="btnDownLoad_Click" TabIndex="100" /> <asp:HiddenField ID="hidImageUrl" runat="server" />
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()); } } } }
<a href='#' id='loadimg' onclick=\"downloadFile('sss','" + ImageUrl + "')\" class='btn btn-link text-dec' > 下载</a>
function downloadFile(fileName, content) { $('#ContentPlaceHolder1_hidImageUrl').val(content); $('#ContentPlaceHolder1_btnDownLoad').click(); return false; }
以上代码主要是通过JS代码调用服务器控件的OnClick事件;在后台把图片下载后保存至Response流中;实现类似下载Excel文件的功能