/// <summary> /// Post image /// </summary> /// <param name="url"></param> /// <param name="data"></param> /// <param name="imgRaw"></param> public void PostImage( string url, Dictionary<string, object> data, WebPostImageObject media) { byte[] postData = BuildImagePostData(data, media); try { Request = HttpWebRequest.Create(url) as HttpWebRequest; Request.ContentType = string.Concat("multipart/form-data; boundary=", BOUNDARY); Request.Method = "POST"; Request.BeginGetRequestStream( (asyncResult) => OnGetRequestStreamCallback(asyncResult, postData), Request); } catch (System.Exception e) { FirePostFailedEvent(e); CleanUp(); } }
/// <summary> /// Build Post data /// </summary> /// <param name="data"></param> /// <param name="imgRaw"></param> /// <returns></returns> internal byte[] BuildImagePostData( Dictionary<string, object> data, WebPostImageObject media) { var sb = new StringBuilder(); foreach (var kv in data) { sb.Append(PREFIX).Append(BOUNDARY).Append(NEWLINE); sb.Append("Content-Disposition: form-data; name=\"").Append(kv.Key).Append("\"").Append(NEWLINE); sb.Append(NEWLINE); sb.Append(kv.Value); sb.Append(NEWLINE); } sb.Append(PREFIX).Append(BOUNDARY).Append(NEWLINE); if (string.IsNullOrEmpty(media.FieldName)) sb.Append("Content-Disposition: form-data; filename=\"").Append(media.FileName).Append("\"").Append(NEWLINE); else sb.Append("Content-Disposition: form-data; name=\"").Append(media.FieldName).Append("\";filename=\"").Append(media.FileName).Append("\"").Append(NEWLINE); sb.Append("Content-Type: ").Append(media.ContentType).Append(NEWLINE); sb.Append(NEWLINE); var lastPart = string.Concat(NEWLINE, PREFIX, BOUNDARY, PREFIX, NEWLINE); byte[] headerBytes = Encoding.UTF8.GetBytes(sb.ToString()); byte[] fileData = media.FileData; byte[] lastBytes = Encoding.UTF8.GetBytes(lastPart.ToString()); var postData = new byte[headerBytes.Length + fileData.Length + lastBytes.Length]; Buffer.BlockCopy(headerBytes, 0, postData, 0, headerBytes.Length); Buffer.BlockCopy(fileData, 0, postData, headerBytes.Length, fileData.Length); Buffer.BlockCopy(lastBytes, 0, postData, headerBytes.Length + fileData.Length, lastBytes.Length); return postData; }