【问题标题】:Download large file from URL in .net core web api从.net core web api中的URL下载大文件
【发布时间】: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


【解决方案1】:

IHttpContextAccessor 提供对上下文的访问和使用实现。感谢@mj1313在本论坛指出答案。Link

public class HomeController : Controller
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public HomeController(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }
 

    public async Task<IActionResult> Contact()
    {
       ..

       var resp = _httpContextAccessor.HttpContext.Response;
       resp.Headers.Add("Content-Type", "text/event-stream");

       // Verify that the client is connected.
       if (HttpContext.RequestAborted.IsCancellationRequested == false)
            {
                ..                   
                await resp.Body.WriteAsync(buffer, 0, length); 
                //or await resp.WriteAsync("hello"); 
                               
                resp.Body.Flush();

                ..
            }
       ..
    
    }
}

【讨论】:

    猜你喜欢
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 2020-08-25
    • 1970-01-01
    相关资源
    最近更新 更多