1. 使用WebRequest类下载,代码如下:
WebRequest request = WebRequest.Create("http://www.walnr.com/File/Base64ToFile.exe"); WebResponse response = request.GetResponse(); if (response.ContentType.ToLower().Length > 0) { using (Stream reader = response.GetResponseStream()) { using (FileStream writer = new FileStream(@"D:\Base64ToFile.exe", FileMode.OpenOrCreate, FileAccess.Write)) { byte[] buffer = new byte[1024]; int c = 0; while ((c = reader.Read(buffer, 0, buffer.Length)) > 0) { writer.Write(buffer, 0, c); } } } }
2.采用HttpResponse类下载代码如下:
HttpResponse Response = HttpContext.Current.Response; #region 读取流程 byte[] bytes = Convert.FromBase64String(""); #endregion // 清除缓存区流中的所有内容输出 Response.Clear(); // 设置缓冲输出为true,后台编辑的文件写到内存流中了 Response.Buffer = true; // 设置编码格式 ContentEncoding是管字节流到文本的,而Charset是管在浏览器中显示的 //Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); Response.Charset = "UTF-8"; // 将HTTP头添加到输出流,指定默认名 Response.AddHeader("Content-Disposition", string.Format(@"attachment;filename=""{0}""", HttpUtility.UrlEncode("文件.et"))); Response.ContentEncoding = System.Text.Encoding.UTF8; // 设置输出流的HTTP MIME类型为application/vnd.ms-excel //ContentType类型的地址: https://www.cnblogs.com/zzr-stdio/p/10692497.html Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Length", bytes.Length.ToString()); // 将指定的文件写入HTTP内容输出流 Response.OutputStream.Write(bytes, 0, bytes.Length); //防止文件名含中文出现乱码而进行编码 // Response.BinaryWrite(bytes); // 向客户端发送当前所有缓冲的输出 Response.Flush(); // 将当前所有缓冲的输出关闭 Response.Close();
标签:输出,HTTP,C#,bytes,几种,buffer,Length,Response,下载 From: https://www.cnblogs.com/lgx5/p/17015127.html