最近boss让写一个二维码的生成器,但是二维码生成后用户如果想下载二维码,这就促使我写l了 下载功能,小弟自认为技术不咋样,是个彻头彻尾的码农,本先是想用js来实现功能,但是查找了好多资料也没能实现,最后还是想到了后台代码。。。
好了废话就不多说了下面看代码吧....
首先在前台页面加上一个
<asp:LinkButton runat="server" onclick="Unnamed1_Click">LinkButton</asp:LinkButton>
然后就是他的后台代码了
protected void Unnamed1_Click(object sender, EventArgs e) { string s_fileName = "/img/1.jpg"; //图片路径 HttpContext.Current.Response.ContentType = "application/ms-download"; //声明方式 string s_path = HttpContext.Current.Server.MapPath("~/") + s_fileName; 找到文件路径 System.IO.FileInfo file = new System.IO.FileInfo(s_path); //打开文件位置 HttpContext.Current.Response.Clear(); HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream"); //声明方式 HttpContext.Current.Response.Charset = "utf-8"; //声明方式 HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(file.Name, System.Text.Encoding.UTF8)); HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString()); HttpContext.Current.Response.WriteFile(file.FullName); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.End(); }