5

In my Windows Store App (c#) I need to upload MultipartFormDataContent (some strings content and some files) to server and get a huge file at response. The problem - I can't use BackgroundDownloaders for that. I can only use one request for that.

I use HttpClient.PostAsync method:

 using (var client = new HttpClient(httpClientHandler))
            {
                using (var content = new MultipartFormDataContent())
                {
                    content.Add(...); // prepare all strings and files content
                    try
                    {
                        using (var response = await client.PostAsync(url, content))
                        {
                            if (response.StatusCode == HttpStatusCode.OK)
                            {
                                var inputBytes = await response.Content.ReadAsByteArrayAsync();
                                // some operations with inputBytes 
                            }
                            ......
                        }
                    }
                }
            }

My question is: How can I calculate progress of this operation?

Note: My target - Windows 8. And I can't use Windows.Web.Http.HttpClient (Minimum supported client Windows 8.1). Only System.Net.Http.HttpClient

2 Answers 2

12

I faced same issue. I fixed it by implementing custom HttpContent. I use this object to track percentage of upload progress, you can add an event to and listen it. You should customize SerializeToStreamAsync method.

internal class ProgressableStreamContent : HttpContent
{
    private const int defaultBufferSize = 4096;

    private Stream content;
    private int bufferSize;
    private bool contentConsumed;
    private Download downloader;

    public ProgressableStreamContent(Stream content, Download downloader) : this(content, defaultBufferSize, downloader) {}

    public ProgressableStreamContent(Stream content, int bufferSize, Download downloader)
    {
        if(content == null)
        {
            throw new ArgumentNullException("content");
        }
        if(bufferSize <= 0)
        {
            throw new ArgumentOutOfRangeException("bufferSize");
        }

        this.content = content;
        this.bufferSize = bufferSize;
        this.downloader = downloader;
    }

    protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
    {
        Contract.Assert(stream != null);

        PrepareContent();

        return Task.Run(() =>
        {
            var buffer = new Byte[this.bufferSize];
            var size = content.Length;
            var uploaded = 0;

            downloader.ChangeState(DownloadState.PendingUpload);

            using(content) while(true)
            {
                var length = content.Read(buffer, 0, buffer.Length);
                if(length <= 0) break;

                downloader.Uploaded = uploaded += length;

                stream.Write(buffer, 0, length);

                downloader.ChangeState(DownloadState.Uploading);
            }

            downloader.ChangeState(DownloadState.PendingResponse);
        });
    }

    protected override bool TryComputeLength(out long length)
    {
        length = content.Length;
        return true;
    }

    protected override void Dispose(bool disposing)
    {
        if(disposing)
        {
            content.Dispose();
        }
        base.Dispose(disposing);
    }


    private void PrepareContent()
    {
        if(contentConsumed)
        {
            // If the content needs to be written to a target stream a 2nd time, then the stream must support
            // seeking (e.g. a FileStream), otherwise the stream can't be copied a second time to a target 
            // stream (e.g. a NetworkStream).
            if(content.CanSeek)
            {
                content.Position = 0;
            }
            else
            {
                throw new InvalidOperationException("SR.net_http_content_stream_already_read");
            }
        }

        contentConsumed = true;
    }
}

Just for reference:

public interface IDownload
{
    event EventHandler<DownloadStateEventArgs> StateChanged;
    event EventHandler<DownloadStateEventArgs> Completed;

    DownloadState State { get; }
    Guid Id { get; }
    string Uri { get; }
    long Filesize { get; }
    long Downloaded { get; }

    Task DownloadAsync();
}
6
  • 5
    This solution works perfectly. Just remember, if you are using Xamarin, to include the Microsoft.Net.Http nuget package in the .iOS project otherwise you'll get a TypeLoadException when initialising this class Oct 27, 2015 at 6:47
  • 1
    what is Download downloader? Dec 29, 2016 at 11:16
  • @HeisenBerg it's a simple object that I use to report download status etc. Dec 29, 2016 at 11:23
  • Thank you. Can you please take a look at this topic? stackoverflow.com/questions/41378457/… Dec 29, 2016 at 11:25
  • 3
    This does not work (anymore). It will go through the whole request in "SerializeToStreamAsync" and only then start using the bandwidth and actually uploading it.
    – Legion
    Jul 15, 2020 at 16:45
4

The WebAPI Client nuget has some classes for doing this. Take a look at the ProgressMessageHandler. It is a PCL library so it should run fine for a Windows Store App.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.