使用 ASP.Net 框架 2.0 异步流式传输大型文件



我正在开发一个 ASP.NET 框架 2.0 应用程序。在特定页面上,我为用户提供了链接。单击此链接将打开一个窗口,其中包含另一个 aspx 页。此页面实际上将 http 请求发送到指向文件的第三方 url(如 - 镜像 urls 从云下载文件)。http 响应在第一页上使用 response.write 从用户单击链接的位置发送回用户。

现在,我面临的问题是,如果文件大小很小,那么它可以正常工作。但是,如果文件很大(即超过 1 GB),那么我的应用程序会等到从 URL 下载整个文件。我尝试使用 response.flush() 将逐块数据发送给用户,但用户仍然无法使用应用程序,因为工作进程正忙于从第三方 URL 获取数据流。

有什么方法可以异步下载大文件,以便我的弹出窗口完成其执行(下载正在进行中),并且用户还可以在应用程序并行上执行其他活动。

谢谢 苏沃迪普

使用 WebClient 读取远程文件。您可以从 Web 客户端获取流,而不是下载。将其放入 while() 循环中,并在响应流中推送来自 WebClient 流的字节。这样,您将同时异步下载和上传。

HttpRequest 示例:

private void WriteFileInDownloadDirectly()
{
//Create a stream for the file
Stream stream = null;
//This controls how many bytes to read at a time and send to the client
int bytesToRead = 10000;
// Buffer to read bytes in chunk size specified above
byte[] buffer = new byte[bytesToRead];
// The number of bytes read
try
{
//Create a WebRequest to get the file
HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create("Remote File URL");
//Create a response for this request
HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
if (fileReq.ContentLength > 0)
fileResp.ContentLength = fileReq.ContentLength;
//Get the Stream returned from the response
stream = fileResp.GetResponseStream();
// prepare the response to the client. resp is the client Response
var resp = HttpContext.Current.Response;
//Indicate the type of data being sent
resp.ContentType = "application/octet-stream";
//Name the file 
resp.AddHeader("Content-Disposition", $"attachment; filename="{ Path.GetFileName("Local File Path - can be fake") }"");
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
int length;
do
{
// Verify that the client is connected.
if (resp.IsClientConnected)
{
// Read data into the buffer.
length = stream.Read(buffer, 0, bytesToRead);
// and write it out to the response's output stream
resp.OutputStream.Write(buffer, 0, length);
// Flush the data
resp.Flush();
//Clear the buffer
buffer = new byte[bytesToRead];
}
else
{
// cancel the download if client has disconnected
length = -1;
}
} while (length > 0); //Repeat until no data is read
}
finally
{
if (stream != null)
{
//Close the input stream
stream.Close();
}
}
}

网络客户端流阅读:

using (WebClient client = new WebClient())
{
Stream largeFileStream = client.OpenRead("My Address");
}

最新更新