1.方法一:WebRequest下载,下载路径包含http
/// <summary> /// 网络文件下载 /// </summary> /// <param name="p_strUrl">网络地址</param> /// <param name="saveFileName">文件名称</param> /// <returns>true-下载成功 false-下载失败</returns> /// </remarks> public static bool FileDownload(string p_strUrl, string saveFileName) { try { WebRequest webRequest = WebRequest.Create(p_strUrl); //读取文件流 Stream stream = webRequest.GetResponse().GetResponseStream(); byte[] fileByte = new byte[512]; MemoryStream ms = new MemoryStream(); int index = 0; while (true) { index = stream.Read(fileByte, 0, fileByte.Length); if (index == 0) { break; } //写进内存流 ms.Write(fileByte, 0, index); } byte[] array = ms.ToArray(); saveFileName = string.IsNullOrEmpty(saveFileName) == true ? p_strUrl.Split('/')[p_strUrl.Split('/').Length - 1] : saveFileName; //添加文件头 // 判断浏览器类型添加文件头 update by X.Y if (HttpContext.Current.Request.UserAgent.ToLower().IndexOf("msie") > -1) { saveFileName = ToHexString(saveFileName); } if (HttpContext.Current.Request.UserAgent.ToLower().IndexOf("firefox") > -1) { HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename="" + saveFileName + """); } else { HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + saveFileName); } System.Web.HttpContext.Current.Response.AddHeader("Content-Length", array.Length.ToString()); System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream"; System.Web.HttpContext.Current.Response.Charset = "UTF-8"; System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8; System.Web.HttpContext.Current.Response.BinaryWrite(array); System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.Clear(); } catch { return false; } return true; }
2.方法二:文件流下载方法,下载路径不包含http
/// <summary> /// 功能: 输出文件 /// </summary> /// <param name="fileHttpUrl">文件网络地址</param> /// <param name="saveFileName">保存默认文件名</param> public void ResponseWriteFile(string fileHttpUrl, string saveFileName) { try { // 创建文件信息实体 FileInfo fileInfo = new FileInfo(fileHttpUrl); saveFileName = string.IsNullOrEmpty(saveFileName) == true ? fileHttpUrl.Split('/')[fileHttpUrl.Split('/').Length - 1] : saveFileName; if (fileInfo.Exists == true) { //每次只读取100K const long unitSize = 102400; byte[] buffer = new byte[unitSize]; // 清空Response HttpContext.Current.Response.Clear(); // 创建文件流 FileStream fileStream = File.OpenRead(fileHttpUrl); long fileLength = fileStream.Length; HttpContext.Current.Response.ContentType = "application/octet-stream"; // 判断浏览器类型添加文件头 if (HttpContext.Current.Request.UserAgent.ToLower().IndexOf("msie") > -1) { saveFileName = ToHexString(saveFileName); } if (HttpContext.Current.Request.UserAgent.ToLower().IndexOf("firefox") > -1) { HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename="" + saveFileName + """); } else { HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + saveFileName); } // 循环输出文件 while (fileLength > 0 && HttpContext.Current.Response.IsClientConnected) { int readLength = fileStream.Read(buffer, 0, Convert.ToInt32(unitSize)); HttpContext.Current.Response.OutputStream.Write(buffer, 0, readLength); HttpContext.Current.Response.Flush(); fileLength = fileLength - readLength; } HttpContext.Current.Response.Close(); } else { //("下载失败,文件不存在!"); } } catch(Exception ex) { //("下载失败,请联系管理员或重试!"); } }
3.编码
/// <summary> /// Encodes non-US-ASCII characters in a string. /// </summary> /// <param name="s"></param> /// <returns></returns> public static 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> /// Determines if the character needs to be encoded. /// </summary> /// <param name="chr"></param> /// <returns></returns> private static bool NeedToEncode(char chr) { string reservedChars = "$-_.+!*'(),@=&"; if (chr > 127) return true; if (char.IsLetterOrDigit(chr) || reservedChars.IndexOf(chr) >= 0) return false; return true; } /// <summary> /// Encodes a non-US-ASCII character. /// </summary> /// <param name="chr"></param> /// <returns></returns> private static 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(); }