asp.net实现下载的问题
数据库中路径存的是这样的:/upload/2012/7/26/R_SFTM-CF_2011083002030724.xls
要实现在前台点击按钮下载文件
我在项目里用LinkButton还是用hyperlink呢?
赋值的时候是直接赋查出来的路径呢?
还是查出来的路径要做些处理呢?
[解决办法]
路径就用相对的,如果你不希望下载时被用户看到你的实际路径 就在后台处理下载
HyperLink 就是一个普通A标记 如果直接赋值是可以看到附件位置
LinkButton 也是A标记不过有点击事件会 回发到后台
我给你一个后台下载的代码
protected void btnTest_Click(object sender, EventArgs e) { DownLoadFile("~/template.txt"); } /// <summary> /// 下载文件 /// </summary> /// <param name="fileName"></param> protected void DownLoadFile(string fileName) { try { string FullFileName = Server.MapPath(fileName); //FileName--要下载的文件名 FileInfo DownloadFile = new FileInfo(FullFileName); if (DownloadFile.Exists) { Response.Clear(); Response.ClearHeaders(); Response.Buffer = false; Response.ContentType = "application/octet-stream"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + ToHexString(DownloadFile.Name)); Response.AppendHeader("Content-Length", DownloadFile.Length.ToString()); Response.WriteFile(DownloadFile.FullName); Response.Flush(); Response.End(); } } catch { } } /// <summary> /// 为字符串中的非英文字符编码 /// </summary> /// <param name="s"></param> /// <returns></returns> public string ToHexString(string s) { char[] chars = s.ToCharArray(); StringBuilder builder = new StringBuilder(); for (int index = 0; index < chars.Length; index++) { bool needToEncode = NeedToEncode(chars[index]); if (needToEncode) { string encodedString = ToHexString(chars[index]); builder.Append(encodedString); } else { builder.Append(chars[index]); } } return builder.ToString(); } /// <summary> ///指定 一个字符是否应该被编码 /// </summary> /// <param name="chr"></param> /// <returns></returns> private bool NeedToEncode(char chr) { string reservedChars = "$-_.+!*'(),@=&"; if (chr > 127) return true; if (char.IsLetterOrDigit(chr) || reservedChars.IndexOf(chr) >= 0) return false; return true; } /// <summary> /// 为非英文字符串编码 /// </summary> /// <param name="chr"></param> /// <returns></returns> private string ToHexString(char chr) { UTF8Encoding utf8 = new UTF8Encoding(); byte[] encodedBytes = utf8.GetBytes(chr.ToString()); StringBuilder builder = new StringBuilder(); for (int index = 0; index < encodedBytes.Length; index++) { builder.AppendFormat("%{0}", Convert.ToString(encodedBytes[index], 16)); } return builder.ToString(); }