httpclient上傳文件進度顯示

httpclient上傳文件帶有進度的功能,通過傳遞一個action來更新界面的UI,做到進度展示

 try
            {

                string filename = @"D:\test.exe";
                HttpClient httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Add("Authorization", "");
                MultipartFormDataContent form = new MultipartFormDataContent();
                form.Add(new StringContent(new FileInfo(filename).Name), "filename");

                byte[] fbt = System.IO.File.ReadAllBytes(filename);
                form.Add(new ProgressableHttpContent(new ByteArrayContent(fbt), 1024 * 10, new ProgressUI((uploadSize, totalSize) =>
                {
                    int progress = Convert.ToInt32(Math.Round(Convert.ToDouble(uploadSize * 100 / totalSize), 0));
                    SetText(progress.ToString());
                }, fbt.Length)), "file", new FileInfo(filename).Name);
                HttpResponseMessage response = await httpClient.PostAsync("", form);
                var data = await response.Content.ReadAsStringAsync();

            }
            catch (Exception ex)
            {

            }




 

 delegate void delegate1(string text);

        private void SetText(string text)
        {
            if (this.textBox1.InvokeRequired)
            {
                delegate1 d = new delegate1(SetText);
                this.textBox1.Invoke(d, new object[] { text });
            }
            else
            {
                this.textBox1.Text = text;
            }
        }

 

    public class ProgressableHttpContent : HttpContent
    {
        private const int DEFAULT_BUFFER_SIZE = 5 * 4096; // 20KB

        private HttpContent _content;
        private int _bufferSize;
        private IProgress<long> _progress;

        /// <summary>
        /// Creates a proxy-like http content that reports its progress when it gets converted into a stream (e.g. when it uploads).
        /// The progress will be reported as a <see cref="UInt64"/> which represents the total bytes sent at this point.
        /// </summary>
        /// <param name="content">The original http content to send</param>
        /// <param name="progress">The progress implemetation for receiving progress updates</param>
        public ProgressableHttpContent(HttpContent content, IProgress<long> progress)
            : this(content, DEFAULT_BUFFER_SIZE, progress) { }

        /// <summary>
        /// Creates a proxy-like http content that reports its progress when it gets converted into a stream (e.g. when it uploads).
        /// The progress will be reported as a <see cref="UInt64"/> which represents the total bytes sent at this point.
        /// </summary>
        /// <param name="content">The original http content to send</param>
        /// <param name="bufferSize">The buffer size used to copy the stream to the requester</param>
        /// <param name="progress">The progress implemetation for receiving progress updates</param>
        public ProgressableHttpContent(HttpContent content, int bufferSize, IProgress<long> progress)
        {
            if (bufferSize <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(bufferSize));
            }

            _content = content ?? throw new ArgumentNullException(nameof(content));
            _bufferSize = bufferSize;
            _progress = progress ?? throw new ArgumentNullException(nameof(progress));

            foreach (var header in content.Headers)
            {
                Headers.Add(header.Key, header.Value);
            }
        }

        protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            using (var contentStream = await _content.ReadAsStreamAsync())
            {
                await contentStream.CopyToAsync(stream, _bufferSize, _progress);
            }
        }

        protected override bool TryComputeLength(out long length)
        {
            length = _content.Headers.ContentLength.GetValueOrDefault();
            return _content.Headers.ContentLength.HasValue;
        }

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


    public class ProgressUI : IProgress<long>
    {
        private Action<long,long> action;
        private long totalSize;
        public ProgressUI(Action<long, long> action,long totalSize)
        {
            this.action = action;
            this.totalSize = totalSize;
        }
        public void Report(long value)
        {
            if (action != null)
            {
                action(value, totalSize);
            }
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章