123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 |
- /* ==============================================================================
- * 功能描述:PutFlieContent
- * 创 建 者:Garrett
- * 创建日期:2019/9/16 19:24:43
- * ==============================================================================*/
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Threading.Tasks;
- namespace PackageUploader.Http
- {
- /// <summary>
- /// PutFlieContent
- /// </summary>
- class PutFlieContent : FileContent
- {
- private string m_Url;
- private Stream m_Stream;
- public PutFlieContent(string url, Stream stream)
- {
- m_Url = url;
- m_Stream = stream;
- }
- /// <summary>
- /// 上传文件
- /// </summary>
- /// <returns></returns>
- public virtual string PutContent()
- {
- var url = m_Url;
- var stream = m_Stream;
- if (stream == null)
- throw new ArgumentNullException(nameof(stream));
- var responseValue = string.Empty;
- HttpWebRequest request = null;
- try
- {
- var totalLength = stream.Length;
- request = (HttpWebRequest)WebRequest.Create(url);
- request.KeepAlive = true;
- request.Timeout = Timeout;
- request.Method = "POST";
- request.ContentLength = totalLength;
- request.ContentType = "multipart/form-data; ";
- #region 请求数据
- byte[] buffer = new byte[BufferLength];
- var transLength = 0;
- using (BinaryReader r = new BinaryReader(stream))
- {
- Stream postStream = request.GetRequestStream();
- try
- {
- int size = 0;
- do
- {
- size = r.Read(buffer, 0, buffer.Length);
- postStream.Write(buffer, 0, size);
- transLength += size;
- #region 调用事件
- StreamProgressArgs args = new StreamProgressArgs(size, transLength, totalLength);
- args.TransCompleted = (size == (long)0);
- TransferProgress?.Invoke(this, args);
- #endregion
- } while (size > 0);
- }
- finally
- {
- postStream?.Close();
- }
- }
- #endregion
- #region 相应数据
- //返回数据
- using (var response = (HttpWebResponse)request.GetResponse())
- {
- if (response.StatusCode != HttpStatusCode.OK)
- {
- var message = String.Format("请求失败. 获得http状态 {0}", response.StatusCode);
- throw new ApplicationException(message);
- }
- using (var responseStream = response.GetResponseStream())
- {
- if (responseStream != null)
- using (var reader = new StreamReader(responseStream))
- {
- responseValue = reader.ReadToEnd();
- }
- }
- }
- #endregion
- }
- catch (Exception e)
- {
- throw;
- }
- finally
- {
- //request?.dis
- }
- return responseValue;
- }
- }
- }
|