Response.AddHeader("Content-Length", iStream.Length.ToString());
public void download()
{
string fileName = "456.zip";//客户端保存的文件名
string filePath = AppDomain.CurrentDomain.BaseDirectory.Replace("\", "/") + "Excel/123.zip";
System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
if (fileInfo.Exists == true)
{
//每次读取文件,只读取1M,这样可以缓解服务器的压力
const long ChunkSize = 1048576;
byte[] buffer = new byte[ChunkSize];
Response.Clear();
//获取文件
System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
//获取下载的文件总大小
long dataLengthToRead = iStream.Length;
//二进制流数据(如常见的文件下载)
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
//加上设置大小下载下来的.xlsx文件打开时才不会报“Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃”
Response.AddHeader("Content-Length", iStream.Length.ToString());
using (iStream)//解决文件占用问题,using 外 iStream.Dispose() 无法释放文件
{
while (dataLengthToRead > 0 && Response.IsClientConnected)
{
int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小
Response.OutputStream.Write(buffer, 0, lengthRead);
Response.Flush();
dataLengthToRead = dataLengthToRead - lengthRead;
}
iStream.Dispose();
iStream.Close();
}
Response.Close();
Response.End();
}
}
public void downFile(string sourceDoc)
{
//获取文件扩展名
string docExtendName = System.IO.Path.GetExtension(sourceDoc).ToLower();
System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(sourceDoc);
System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
long totalBytes = myrp.ContentLength;
System.IO.Stream st = myrp.GetResponseStream();
string path = System.Web.HttpContext.Current.Server.MapPath("文档" + docExtendName);
System.IO.Stream so = new System.IO.FileStream(path, System.IO.FileMode.Create);
totalDownloadedByte = 0;
byte[] by = new byte[1024];
int osize = st.Read(by, 0, (int)by.Length);
DateTime dt1 = DateTime.Now;
int k = 0;
while (osize > 0)
{
if (k > 10)
{
totalDownloadedByte = 0;
logbyte = 0;
break;
}
DateTime dt2 = DateTime.Now;
if ((dt2 - dt1).Seconds > 1)
{
dt1 = dt2;
logbyte = totalDownloadedByte;
k++;
}
totalDownloadedByte = osize + totalDownloadedByte;
so.Write(by, 0, osize);
osize = st.Read(by, 0, (int)by.Length);
}
so.Close();
so.Dispose();
st.Close();
st.Dispose();
}