标签:网络流 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