2

I want to return a large file in my ASP.Net Web API Controller, but I do not want to load the entire file on the server RAM. Is there a way to return the file in pieces?

Saman Azadi
  • 116
  • 1
  • 6
  • Maybe you can refer to the [link](https://stackoverflow.com/questions/53123243/uploading-large-files-to-controller-in-chunks-using-httpclient-iformfile-always),and check `NuclearProgrammer`'s answer. – Yiyi You Jun 08 '21 at 05:56
  • The old Asp.Net Web API supports [ByteRangeStreamContent](https://devblogs.microsoft.com/aspnet/asp-net-web-api-and-http-byte-range-support/). The newer Asp.Net Core supports [streaming the response](https://stackoverflow.com/a/42772150/458354). – mdisibio Jun 17 '21 at 01:00

1 Answers1

0

You might like to check below code.

    public IHttpActionResult Get()
    {
        var filePath = @"D:\Some Large File.zip";
        var fileStream = new FileStream(filePath, FileMode.Open);
        var result = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StreamContent(fileStream)
        };
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "Some Large File.zip"
        };
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        var response = ResponseMessage(result);
        return response;
    }
MrMoeinM
  • 2,080
  • 1
  • 11
  • 16
  • I am not sure this is right, because the stream is not disposed. See this question, which has shorter, more up-to-date code, but also points out the problem: https://stackoverflow.com/questions/39391953/how-to-dispose-file-stream-in-api – MikeBeaton Apr 28 '23 at 13:56
  • 1
    @MikeBeaton I suspected that before and I tested it. ASP.Net MVC will dispose the stream when the connection is closed or the entire file is sent. – MrMoeinM Apr 28 '23 at 16:06
  • Okay, that _is_ good - thanks. But then, still from that other post, there still might be an issue _if_ you have a situation where a second request tries to get the file while the first request is still reading it? (Which I would agree might not be an issue, in some use cases; but might be in others!) – MikeBeaton May 01 '23 at 21:45
  • 1
    @MikeBeaton That is not a problem either. You can open one file multiple times with only read permission. – MrMoeinM May 02 '23 at 06:29