HTTPMultiPartForm.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using BestHTTP.Extensions;
  2. namespace BestHTTP.Forms
  3. {
  4. /// <summary>
  5. /// A HTTP Form implementation to send textual and binary values.
  6. /// </summary>
  7. public sealed class HTTPMultiPartForm : HTTPFormBase
  8. {
  9. #region Private Fields
  10. /// <summary>
  11. /// A random boundary generated in the constructor.
  12. /// </summary>
  13. private string Boundary;
  14. /// <summary>
  15. ///
  16. /// </summary>
  17. private byte[] CachedData;
  18. #endregion
  19. public HTTPMultiPartForm()
  20. {
  21. this.Boundary = "BestHTTP_HTTPMultiPartForm_" + this.GetHashCode().ToString("X");
  22. }
  23. #region IHTTPForm Implementation
  24. public override void PrepareRequest(HTTPRequest request)
  25. {
  26. // SaveLocal up Content-Type header for the request
  27. request.SetHeader("Content-Type", "multipart/form-data; boundary=\"" + Boundary + "\"");
  28. }
  29. public override byte[] GetData()
  30. {
  31. if (CachedData != null)
  32. return CachedData;
  33. using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
  34. {
  35. for (int i = 0; i < Fields.Count; ++i)
  36. {
  37. HTTPFieldData field = Fields[i];
  38. // SaveLocal the boundary
  39. ms.WriteLine("--" + Boundary);
  40. // SaveLocal up Content-Disposition header to our form with the name
  41. ms.WriteLine("Content-Disposition: form-data; name=\"" + field.Name + "\"" + (!string.IsNullOrEmpty(field.FileName) ? "; filename=\"" + field.FileName + "\"" : string.Empty));
  42. // SaveLocal up Content-Type head for the form.
  43. if (!string.IsNullOrEmpty(field.MimeType))
  44. ms.WriteLine("Content-Type: " + field.MimeType);
  45. ms.WriteLine("Content-Length: " + field.Payload.Length.ToString());
  46. ms.WriteLine();
  47. // Write the actual data to the MemoryStream
  48. ms.Write(field.Payload, 0, field.Payload.Length);
  49. ms.Write(HTTPRequest.EOL, 0, HTTPRequest.EOL.Length);
  50. }
  51. // Write out the trailing boundary
  52. ms.WriteLine("--" + Boundary + "--");
  53. IsChanged = false;
  54. // SaveLocal the RawData of our request
  55. return CachedData = ms.ToArray();
  56. }
  57. }
  58. #endregion
  59. };
  60. }