【发布时间】:2020-10-10 01:45:13
【问题描述】:
在 .net 框架 4.7 中,我能够使用此逻辑从另一个 URL(在块中)流式传输文件,但在 .net 核心 System.Web.HttpContext 和 HttpResponse 中不可用。任何帮助,以实现从另一个 URL 分块下载的目标,在 .net core 3.1 中。 .net core 中没有 HttpContext.Current.Response 、 IsClientConnected 等,
//Create a stream for the file
Stream stream = null;
//chunk of 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 = HttpContext.Current.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)
{
stream.Close();
}
}
【问题讨论】:
-
有同样的问题here,可以参考这个。
标签: .net .net-core asp.net-core-webapi