从.NET Core Web API中的URL下载大文件 [英] Download large file from URL in .net core web api

查看:1158
本文介绍了从.NET Core Web API中的URL下载大文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.net framework 4.7中,我能够使用此逻辑从另一个URL(在Chunks中)流式传输文件,但是在.net核心System.Web.HttpContext和HttpResponse中不可用.为了达到从.net core 3.1中从另一个URL批量下载的目的,需要任何帮助. NET环境中HttpContext.Current.Response,IsClientConnected等不可用

In .net framework 4.7, I was able to use this logic to stream file from another URL (in Chunks), but in .net core System.Web.HttpContext and HttpResponse are not available. Any help pls, to achieve this objective of downloading in chunks from another URL, in .net core 3.1. The HttpContext.Current.Response , IsClientConnected etc are not available in .net core,

//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();
    }
}

推荐答案

IHttpContextAccessor提供对上下文的访问并使用实现.感谢@ mj1313在此论坛中指出答案.,

IHttpContextAccessor provides access to context and use the implementation. Thanks to @mj1313 for pointing out the answer in this forum., 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();

                ..
            }
       ..
    
    }
}

这篇关于从.NET Core Web API中的URL下载大文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆