调用下载函数下载到了我的页面?
哪位大虾帮我看一下这个下载方法。怎么用vs调试时可以争取下载文件,用iis时就把我的页面个下载过来了。怎么避免下载我的页面?
public static bool DowndLoadFile(string _fileName, string _fullPath, long _speed)
{
if (!File.Exists(_fullPath))//文件不存在
{
System.Web.HttpContext.Current.Response.Write("<script language='javascript'>alert('文件不存在,下载失败');</script>");
return false;
}
try
{
System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
try
{
response.AddHeader("Accept-Ranges", "bytes");
response.Buffer = false;
long fileLength = myFile.Length;
long startBytes = 0;
int pack = 10240; //10K bytes
double sleepnum = 1000 * pack / _speed;
//int sleep = 200; //每秒5次 即5*10K bytes每秒
int sleep = (int)Math.Floor(sleepnum) + 1;
if (request.Headers["Range"] != null)
{
response.StatusCode = 206;
string[] range = request.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[1]);
}
response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != 0)
{
response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
}
response.AddHeader("Connection", "Keep-Alive");
response.ContentType = "application/octet-stream";
response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));
br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
double num = (fileLength - startBytes) / pack;
int maxCount = (int)Math.Floor(num) + 1;
for (int i = 0; i < maxCount; i++)
{
if (response.IsClientConnected)
{
response.BinaryWrite(br.ReadBytes(pack));
System.Threading.Thread.Sleep(sleep);
}
else
{
i = maxCount;
}
}
}
catch (Exception ex)
{
CreateErrorLog(ex);
return false;
}
finally
{
br.Close();
myFile.Close();
}
}
catch (Exception ex)
{
CreateErrorLog(ex);
return false;
}
return true;
}
[解决办法]
是不是文件路径错了,