HTTPMultiPartForm.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. // Set 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 (var ms = new BufferPoolMemoryStream())
  34. {
  35. for (int i = 0; i < Fields.Count; ++i)
  36. {
  37. HTTPFieldData field = Fields[i];
  38. // Set the boundary
  39. ms.WriteLine("--" + Boundary);
  40. // Set 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. // Set up Content-Type head for the form.
  43. if (!string.IsNullOrEmpty(field.MimeType))
  44. ms.WriteLine("Content-Type: " + field.MimeType);
  45. ms.WriteLine();
  46. // Write the actual data to the MemoryStream
  47. ms.Write(field.Payload, 0, field.Payload.Length);
  48. ms.Write(HTTPRequest.EOL, 0, HTTPRequest.EOL.Length);
  49. }
  50. // Write out the trailing boundary
  51. ms.WriteLine("--" + Boundary + "--");
  52. IsChanged = false;
  53. // Set the RawData of our request
  54. return CachedData = ms.ToArray();
  55. }
  56. }
  57. #endregion
  58. };
  59. }