29 using System.Collections.Generic;
34 namespace OpenSim.Framework
36 public static class MultipartForm
38 #region Helper Classes
51 public File(
string name,
string filename,
string contentType, byte[] data)
55 ContentType = contentType;
71 #endregion Helper Classes
73 public static HttpWebResponse Post(HttpWebRequest request, List<Element> postParameters)
75 string boundary = Boundary();
78 request.Method =
"POST";
79 request.ContentType =
"multipart/form-data; boundary=" + boundary;
81 #region Stream Writing
83 using (MemoryStream formDataStream =
new MemoryStream())
85 foreach (var param
in postParameters)
89 File file = (File)param;
92 string header = string.Format(
"--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",
95 !String.IsNullOrEmpty(file.Filename) ? file.Filename :
"tempfile",
98 formDataStream.Write(Encoding.UTF8.GetBytes(header), 0, header.Length);
99 formDataStream.Write(file.Data, 0, file.Data.Length);
103 Parameter parameter = (Parameter)param;
105 string postData = string.Format(
"--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n",
109 formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, postData.Length);
114 byte[] footer = Encoding.UTF8.GetBytes(
"\r\n--" + boundary +
"--\r\n");
115 formDataStream.Write(footer, 0, footer.Length);
117 request.ContentLength = formDataStream.Length;
120 formDataStream.Seek(0, SeekOrigin.Begin);
121 using (Stream requestStream = request.GetRequestStream())
122 formDataStream.CopyStream(requestStream, (int)formDataStream.Length);
125 #endregion Stream Writing
127 return request.GetResponse() as HttpWebResponse;
130 private static string Boundary()
132 Random rnd =
new Random();
133 string formDataBoundary = String.Empty;
135 while (formDataBoundary.Length < 15)
136 formDataBoundary = formDataBoundary + rnd.Next();
138 formDataBoundary = formDataBoundary.Substring(0, 15);
139 formDataBoundary =
"-----------------------------" + formDataBoundary;
141 return formDataBoundary;