问题描述
我已经实现了一个asp.net MVC网站,用户可以下载大型MP3文件(最大120 MB)并且工作正常。但问题是当我们发送文件的下载请求然后下载正常启动但我们不能在网站上执行任何操作,直到文件完全下载(没有得到任何其他请求的任何响应)。如何快速下载文件和另一个请求也一起发送响应下载文件?我的文件存储在Microsoft Azure存储blob上。
我尝试过:
I've implemented an asp.net MVC site where users can download large MP3 files (up to 120 MB) and works fine. But the problem is when we send the download request of the file then downloading starts properly but we can not perform any action on site until the file fully download (not getting any response of any another request). How can I do fast download the file and another request also send the response together downloading files? My files are stored on Microsoft Azure storage blob.
What I have tried:
public async Task<string> DownloadMediaFile(string url)
{
int lstidx = url.LastIndexOf('/');
int charslngth = url.Length - 1;
string getFileNameWithExtension = url.Substring(lstidx + 1, charslngth - lstidx);
string fileName = getFileNameWithExtension;
//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(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 = Response;
//Indicate the type of data being sent
resp.ContentType = "application/octet-stream";
//Name the file
resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
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();
}
}
return "success";
}
推荐答案
[SessionState(SessionStateBehavior.Disabled)]
public class DownloadController : Controller
{
...
这篇关于如何使用C#在MVC中快速下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!