下载网络文件,网络流转换为内存流
Posted roper
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了下载网络文件,网络流转换为内存流相关的知识,希望对你有一定的参考价值。
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;
}
以上是关于下载网络文件,网络流转换为内存流的主要内容,如果未能解决你的问题,请参考以下文章