码迷,mamicode.com
首页 > 其他好文 > 详细

下载网络文件,网络流转换为内存流

时间:2019-11-06 13:13:11      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:网络流   sys   isp   tac   odi   set   http   app   memory   

string fileext = CSA_BLL.Common.Utils.GetFileExt(filePath);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(filePath);
request.Method = "GET";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode == HttpStatusCode.OK)
{
Stream rs = response.GetResponseStream();
//网络流转换为内存流
var ms = StreamToMemoryStream(rs);
ms.Seek(0, SeekOrigin.Begin); int buffsize = (int)ms.Length; //rs.Length 此流不支持查找,先转为MemoryStream
byte[] bytes = new byte[buffsize];

ms.Read(bytes, 0, buffsize);
ms.Flush(); ms.Close();
rs.Flush(); rs.Close();
//以文件流的方式下载
Response.Charset = "utf-8";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.ContentType = "application/octet-stream";
if (HttpContext.Request.UserAgent.ToUpper().Contains("MSIE") ||
HttpContext.Request.UserAgent.ToUpper().Contains("TRIDENT") ||
HttpContext.Request.UserAgent.ToUpper().Contains("EDGE"))
{
fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
}
else
{
fileName = fileName.Replace(" ", "_");
}
//fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(fileName + "." + fileext));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();

}
}
return new EmptyResult();
}

MemoryStream StreamToMemoryStream(Stream instream)
{
MemoryStream outstream = new MemoryStream();
const int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = instream.Read(buffer, 0, bufferLen)) > 0)
{
outstream.Write(buffer, 0, count);
}
return outstream;
}

下载网络文件,网络流转换为内存流

标签:网络流   sys   isp   tac   odi   set   http   app   memory   

原文地址:https://www.cnblogs.com/roper/p/11804190.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!