1. 程式人生 > 其它 >C# WebClient 支援 GZip Deflate, 設定超時, 上傳檔案 multipart/form-data

C# WebClient 支援 GZip Deflate, 設定超時, 上傳檔案 multipart/form-data

    public class GZipWebClient : WebClient
    {
        public GZipWebClient(int timeout = 5000)
        {
            this.Timeout = timeout;
        }

        public int Timeout { get; set; } = 5000;

        protected override WebRequest GetWebRequest(Uri address)
        {
            var request = (HttpWebRequest)base.GetWebRequest(address);
            request.Timeout = Timeout;
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            return request;
        }

        /// <summary>
        /// 上傳檔案 multipart/form-data
        /// </summary>
        /// <param name="url"></param>
        /// <param name="fileName"></param>
        /// <param name="contentType"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public string UploadMultipartFile(string url, string fileName, string contentType = "image/jpeg", string method = "POST")
        {
            var boundary = $"--------------------------{DateTime.Now.Ticks:x}";
            Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);

            var start = $"--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{Path.GetFileName(fileName)}\"\r\nContent-Type: {contentType}\r\n\r\n";
            var end = $"\r\n--{boundary}--\r\n";

            var lst = new List<byte>();
            lst.AddRange(Encoding.GetBytes(start));
            lst.AddRange(File.ReadAllBytes(fileName));
            lst.AddRange(Encoding.GetBytes(end));

            return Encoding.GetString(UploadData(url, method, lst.ToArray()));
        }
    }