当前位置: 代码迷 >> ASP.NET >> ASP.NET文件下载,该如何解决
  详细解决方案

ASP.NET文件下载,该如何解决

热度:5822   发布时间:2013-02-26 00:00:00.0
ASP.NET文件下载
我已经实现了文件上传,是传到本地文件夹里面,然后把上传文件名写到数据库里,现在我用Repeater控件把路径读出来想实现下载功能,用超级连接在读,但是一打开就直接在IE里打开了,比如图片,怎么样才能出现下载的框,求求各位了,否则小弟饭碗不保,小弟是新手,麻烦能说清楚点,谢谢各位了,有多少分送多少分

------解决方案--------------------------------------------------------
private void FileDownload()
{
String FullFileName = Server.MapPath( "文件路径 ");
FileInfo DownloadFile = new FileInfo(FullFileName);
Response.Clear();
Response.ClearHeaders();
Response.Buffer = false;
Response.ContentType = "application/octet-stream ";
Response.AppendHeader( "Content-Disposition ", "attachment;filename= " + HttpUtility.UrlEncode(DownloadFile.FullName, System.Text.Encoding.UTF8));
Response.AppendHeader( "Content-Length ", DownloadFile.Length.ToString());
Response.WriteFile(DownloadFile.FullName);
Response.Flush();
Response.End();
}

------解决方案--------------------------------------------------------
public bool ResponseFile(System.Web.HttpRequest _Request,System.Web.HttpResponse _Response,string _fileName,string _fullPath, long _speed)
{
try
{
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
//int sleep = 200; //每秒5次 即5*10K bytes每秒
int sleep = (int)Math.Floor(1000 * pack / _speed) + 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);
int maxCount = (int) Math.Floor((fileLength - startBytes) / pack) + 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
{
return false;
}
finally
{
br.Close();
myFile.Close();
}
}
catch
{
return false;
}
return true;
}
------解决方案--------------------------------------------------------
支持100M+的下载代码:
try
{
string strDocDir;
string strFile;
strDocDir= "updownload ";
strFile=Request.QueryString[ "strFile "];

System.IO.Stream iStream = null;

// Buffer to read 10K bytes in chunk:
  相关解决方案