Загрузите большой файл по URL-адресу в. net core web api - PullRequest
0 голосов
/ 19 июня 2020

В. net framework 4.7, я смог использовать этот logi c для потоковой передачи файла с другого URL-адреса (фрагментами), но в. net core System.Web.HttpContext и HttpResponse недоступны. Любая помощь, пожалуйста, для достижения этой цели загрузки кусками с другого URL-адреса, в. net core 3.1. HttpContext.Current.Response, IsClientConnected и c недоступны в. 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();
    }
}

1 Ответ

0 голосов
/ 22 июня 2020

IHttpContextAccessor обеспечивает доступ к контексту и использование реализации. Спасибо @ mj1313 за указание ответа на этом форуме. Ссылка

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

                ..
            }
       ..
    
    }
}
...