我想创建一个asp.net下载页面。我从dataservice接收文件作为字节数组。文件大小最大可达10GB。所以我需要“部分”传输文件。
这是我的代码:
Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Disposition", _
"attachment; filename=" & HttpUtility.UrlEncode(file.Name))
Do
If Not Response.IsClientConnected Then
Exit Do
End If
result =ReadByte(offset,length) 'read next byte array
Response.BinaryWrite(fresult.Data)
Response.Flush()
Loop Until 'all bytes read
代码段有效,但我遇到了很大问题。在用户确认浏览器下载对话框之前,下载已经开始。如果用户等待5分钟,他已经下载了10gb文件而没有接受它。
你有解决方案吗?
谢谢
答案 0 :(得分:1)
此代码只需将其更新为从文件而不是Web响应中读取
using (WebResponse fileDownloadResponse = fileToDownload.GetResponse())
{
using (Stream fileStream = fileDownloadResponse.GetResponseStream())
{
using (StreamReader fileStreamReader = new StreamReader(fileStream))
{
context.Response.ContentType = "APPLICATION/OCTET-STREAM";
context.Response.AddHeader("Content-Length", fileDownloadResponse.ContentLength.ToString());
string fileName = Path.GetFileNameWithoutExtension(url);
string fileExtension = Path.GetExtension(fileUriBuilder.Uri.AbsolutePath);
context.Response.AddHeader("Content-Disposition", "attachment; filename="+fileName+fileExtension);
byte[] buffer = new byte[4096];
int byteseq = fileStream.Read(buffer, 0, 4096); while (byteseq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteseq);
context.Response.Flush();
byteseq = fileStream.Read(buffer, 0, 4096);
}
}
}
}