asp.net 下载附件功能的实现
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.UI; 6 using System.Web.UI.WebControls; 7 using System.Data.SqlClient; 8 using System.Data; 9 using System.IO; 10 using System.Text; 11 public partial class CommonPage_File_Mg_Details : System.Web.UI.Page 12 { 13 protected string ReverseString(string s) 14 { 15 char[] chars = s.ToCharArray(); 16 Array.Reverse(chars); 17 return new string(chars); 18 } 19 string downLink = ""; 20 protected void Page_Load(object sender, EventArgs e) 21 { 22 //string Indicator="url="; 23 string url = Request.Url.ToString(); 24 //int index = url.IndexOf(Indicator); 25 //string urlpar = url.Substring(index + Indicator.Length, url.Length - index - Indicator.Length); 26 string s = ""; 27 for (int i = url.Length - 1; i >= 0; i--) 28 { 29 if (url[i] == '=') break; 30 s += url[i]; 31 } 32 s = ReverseString(s); 33 OpreationDB db = new OpreationDB(); 34 35 string sqlStr = "select * from [File] where No ="+s; 36 SqlDataReader dr = db.ExceRead(sqlStr); 37 if (dr.Read()) 38 { 39 //tb1.Text = dr[0].ToString().Trim(); 40 tb1.Text = dr["Fcontent"].ToString().Trim(); 41 downLink = dr["Flink"].ToString();//下载链接 42 } 43 } 44 protected void btn_down_Click(object sender, EventArgs e) 45 { 46 string strFileName =""; 47 int j; 48 for (j = downLink.Length - 1; j >= 0; j--) 49 { 50 if(downLink[j]=='/')break; 51 strFileName += downLink[j]; 52 } 53 strFileName = ReverseString(strFileName); 54 55 string strpath = Server.MapPath("~/" + "App_Data") + "/" + strFileName; 56 FileInfo fi = new FileInfo(strpath); 57 Response.Clear(); 58 Response.ClearHeaders(); 59 Response.Buffer = true; 60 Response.ContentType = "application/octet-stream"; 61 Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fi.Name)); 62 Response.AppendHeader("Content-Length", fi.Length.ToString()); 63 Response.WriteFile(fi.FullName); 64 Response.Flush(); 65 Response.End(); 66 67 } 68 }
其中 Request.Url.ToString();用来获得页面的路径,配合字符串截取,能得到参数No,通过SQL语句查询File表中的 上传附件的链接。然后套用下载附件的代码,实现点击下载功能。
未避免文件名字相同可以把时间戳加到文件名字中.
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: