我在ASP.NET中创建了一个脚本,列出了指定文件夹中的文件。
protected void Page_Load( object sender, EventArgs e ) {
//get file list
DirectoryInfo di = new DirectoryInfo( Server.MapPath( "~/download" ) );
int i = 0;
foreach ( FileInfo fi in di.GetFiles() ) {
HyperLink link = new HyperLink();
link.ID = "HyperLink" + ( i++ );
link.ToolTip = fi.Length.ToString();
link.Text = fi.Name;
link.NavigateUrl = "downloading.aspx?file=" + fi.Name;
Page.Controls.Add( link );
Page.Controls.Add( new LiteralControl( "<br/>" ) );
}
}
在downloading.aspx
文件中,我有:
protected void Page_Load( object sender, EventArgs e ) {
string filename = Request["file"].ToString();
FileDownload( filename, Server.MapPath( "~/download/" + filename ) );
}
/// <summary>
/// Download specified file and his url
/// </summary>
/// <param name="filename"></param>
/// <param name="fileUrl"></param>
private void FileDownload( string filename, string fileUrl ) {
Page.Response.Buffer = true;
Page.Response.Clear();
DownloadFile df = new DownloadFile();
bool success = df.DownloadIt( Page.Response, filename, fileUrl );
if ( !success ) {
Response.Write( "Download error" );
}
Page.Response.End();
}
定义了DownloadIt
方法:
public bool DownloadIt( HttpResponse response, string filename, string fileUrl ) {
if ( response == null ) {
throw new Exception();
}
if ( string.IsNullOrEmpty(filename) ) {
throw new ArgumentNullException( "filename" );
}
try {
response.ContentType = "application/octet-stream";
response.AppendHeader( "Content-Disposition", "attachment; filename=" + filename );
response.TransmitFile( fileUrl );
} catch {
return false;
}
return true;
}
在默认页面的那个列表中,我有一个5-6 MB的文件,当我点击它时,会出现对话框浏览器(带有'保存''打开''取消'按钮),但是有一个字段文件大小为14字节....
为什么?
其他小文件,大小正确显示。
我是否要使用Stream缓冲区?
我用以下代码解决了问题:
try {
FileInfo fileDownload = new FileInfo( fileUrl );
int bufferSize = 0;
bufferSize = (int)fileDownload.Length;
using ( Stream s = new FileStream( fileUrl, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize) ) {
byte[] buffer = new byte[bufferSize];
int count = 0;
int offset = 0;
response.ContentType = "application/octet-stream";
response.AddHeader( "Content-Length", buffer.Length.ToString() );
response.AddHeader( "Content-Disposition", "attachment; filename=" + filename );
while ( ( count = s.Read( buffer, offset, buffer.Length ) ) > 0 ) {
response.OutputStream.Write( buffer, offset, count );
}
bufferSize = 0;
}
} catch {
return false;
}
现在问题变成了具有&gt;的文件。由bufferSize
提供的200 MB是int,它是FileStream
的正确参数。
答案 0 :(得分:2)
尝试,
byte []bytes=System.IO.File.ReadAllBytes(fileUrl);
response.Clear();
response.ClearHeaders();
response.AddHeader("Content-Type","application/octet-stream");
response.AddHeader("Content-Length",bytes.Length.ToString());
response.AddHeader( "Content-Disposition", "attachment; filename=" + filename );
response.BinaryWrite(bytes);
response.Flush();
response.End();
答案 1 :(得分:0)
您可以手动设置Content-Length
标题。有关详细信息,请参阅此问题:Download .xlsx file using Response.TransmitFile()