简体   繁体   中英

C# Web API Upload File Asynchronously

I'm trying to create an API that can run an async process that handles the upload process and immediately returns letting the user know the file upload process has begun. From here, I would like to create an API that would poll asking the status of the upload.

Is this something feasible in the networking space? If not, and I have to wait until the whole file has been processed, is that API still available for multiple requests?

Here is my code so far, currently it gets to a certain byte in the post and fails.

public async Task<IHttpActionResult> Post()
{
    var stream = HttpContext.Current.Request.GetBufferlessInputStream(true);
    // Begin Upload
    Task.Run(() => BeginUpload(stream));

    //  Return upload begin successful
    return Ok($"Upload started! # {0}");
}

private async Task<int> BeginUpload(Stream stream)
{
    using (var reader = new StreamReader(stream))
    {
        var index = 0;
        var buffer = new char[100000000];

        while (!reader.EndOfStream)
        {
            await reader.ReadBlockAsync(buffer, index, 1024);
            index += 1024;
            Debug.Write($"{index}\n");
        }
    }

    return 0;
}

Instead of using Task.Run() you could consider HostingEnvironment.QueueBackgroundWorkItem . For instance:

public IHttpActionResult Post()
    {
        var stream = HttpContext.Current.Request.GetBufferlessInputStream(true);
        // Begin Upload
        HostingEnvironment.QueueBackgroundWorkItem(async cancellationToken => await BeginUpload(stream));

        //  Return upload begin successful
        return Ok($"Upload started! # {0}");
    }

    private async Task BeginUpload(Stream stream)
    {
        using (var reader = new StreamReader(stream))
        {
            var index = 0;
            var buffer = new char[100000000];

            while (!reader.EndOfStream)
            {
                await reader.ReadBlockAsync(buffer, index, 1024);
                index += 1024;
                Debug.Write($"{index}\n");
            }
        }
    }

In this case you don't have to wait until the reader has done its work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM