读书人

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

发布时间: 2012-01-01 23:10:55 作者: rapoo

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:


byte[] buffer = new Byte[300000];

// Length of the file:
int length;

// Total bytes to read:
long dataToRead;

// Identify the file to download including its path.
string filepath = Server.MapPath(strDocDir)+ "\\ "+strFile;

// Identify the file name.
string filename = System.IO.Path.GetFileName(filepath);

// 定义file
System.IO.FileInfo file = new System.IO.FileInfo(filepath);

try
{
// Open the file.
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
System.IO.FileAccess.Read,System.IO.FileShare.Read);


// Total bytes to read:
dataToRead = iStream.Length;

Response.ContentType = "application/octet-stream ";
Response.AddHeader( "Content-Disposition ", "attachment; filename= " + System.Web.HttpUtility.UrlEncode(file.Name,System.Text.Encoding.UTF8));

// Read the bytes.
while (dataToRead > 0)
{
// Verify that the client is connected.
if (Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 300000);

// Write the data to the current output stream.
Response.OutputStream.Write(buffer, 0, length);

// Flush the data to the HTML output.
Response.Flush();

buffer= new Byte[300000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}

}
Response.Clear();
Response.End();
}
catch (Exception ex)
{
// Trap the error, if any.
Response.Write( "Error : " + ex.Message);
Response.Clear();
Response.End();
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
Response.Clear();
Response.End();
}
}
catch
{
Response.Write( " <script language=javascript> alert( '附件不存在 '); </script> ");
Response.Write( " <script language=javascript> window.close(); </script> ");
}
[解决办法]
protected void btn_FileDownload_Click(object sender, EventArgs e)
{
string strFileUploadPath = ConfigurationManager.AppSettings[ "FileUploadPath "].ToString();
string strFileName = lb_FileList.SelectedValue;
string strFilePhysicalPath = Server.MapPath(strFileUploadPath + strFileName);
Response.Clear();
Response.ContentType = "application/octet-stream ";
//attachment表示附件下载
Response.AddHeader( "Content-Disposition ", "attachment;FileName= " + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8));
Response.WriteFile(strFilePhysicalPath);
Response.End();

}
[解决办法]
给你个JS的 是幕白兄 发过的 感觉不错 就收集起来了


<a href= "javascript:DownLoad( 'images/i1.gif ') "> 下载 </a>


<script>

var frm = null;
var timer = null
function DownLoad(url)
{
frm = document.createElement( "IFRAME ");
frm.style.display = "none ";


document.body.appendChild(frm);
frm.contentWindow.location.href = url

timer = setInterval(checkload,200);

}
function checkload(){
if( frm.contentWindow.document.readyState == "complete ")
{
frm.contentWindow.document.execCommand( "SaveAs ");
clearInterval(timer)}
document.body.removeChild(frm);
}


</script>

读书人网 >asp.net

热点推荐