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文件的功能服務器

相關文章
相關標籤/搜索