I use the following piece of code:
Usage
List<IPostDataField> Fields = new List<IPostDataField>();
Fields.Add(new PostDataField() { Name="nameOfTheField", Value="value" }); //simple field
Fields.Add(new PostDataFile() { Name="nameOfTheField", FileName="something.ext", Content = byte[], Type = "mimetype" });
string response = WebrequestManager.PostMultipartRequest(
new PostDataEntities.PostData()
{
Fields = Fields
}
,
"url");
PostMultiPartRequest
public static string PostMultipartRequest(PostData postData, string relativeUrl, IUserCredential userCredential)
{
string returnXmlString = "";
try
{
//Initialisatie request
WebRequest webRequest = HttpWebRequest.Create(string.Format(Settings.Default.Api_baseurl, relativeUrl));
//Credentials
NetworkCredential apiCredentials = userCredential.NetworkCredentials;
webRequest.Credentials = apiCredentials;
webRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(apiCredentials.UserName + ":" + apiCredentials.Password)));
//Post!
webRequest.Method = "POST";
webRequest.ContentType = "multipart/form-data; boundary=";
//Post
//byte[] bytesToWrite = UTF8Encoding.UTF8.GetBytes(multipartData);
string boundary = "";
byte[] data = postData.Export(out boundary);
webRequest.ContentType += boundary;
webRequest.ContentLength = data.Length;
using (Stream xmlStream = webRequest.GetRequestStream())
{
xmlStream.Write(data, 0, data.Length);
}
//webRequest.ContentType = "application/x-www-form-urlencoded";
using (WebResponse response = webRequest.GetResponse())
{
// Display the status
// requestStatus = ((HttpWebResponse)response).StatusDescription;
//Plaats 'response' in stream
using (Stream xmlResponseStream = response.GetResponseStream())
{
//Gebruik streamreader om stream uit te lezen en om te zetten naar string
using (StreamReader reader = new StreamReader(xmlResponseStream))
{
returnXmlString = reader.ReadToEnd();
}
}
}
}
catch (WebException wexc)
{
switch (wexc.Status)
{
case WebExceptionStatus.Success:
case WebExceptionStatus.ProtocolError:
log.Debug("bla", wexc);
break;
default:
log.Warn("bla", wexc);
break;
}
}
catch (Exception exc)
{
log.Error("bla");
}
return returnXmlString;
}
IPostdataField
public interface IPostDataField
{
byte[] Export();
}
PostDataField
public class PostDataField : IPostDataField
{
public string Name { get; set; }
public string Value { get; set; }
#region IPostDataField Members
public byte[] Export()
{
using (MemoryStream stream = new MemoryStream())
{
StreamWriter sw = new StreamWriter(stream);
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", Name));
sb.AppendLine();
sb.AppendLine(Value);
sw.Write(sb.ToString());
sw.Flush();
}
stream.Position = 0;
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, (int)buffer.Length);
return buffer;
}
}
#endregion
}
PostDataFile
public class PostDataFile : IPostDataField
{
public Byte[] Content { get; set; }
public string Name { get; set; }
public string FileName { get; set; }
public string Type { get; set; } // mime type
public byte[] Export()
{
using (MemoryStream stream = new MemoryStream())
{
StreamWriter sw = new StreamWriter(stream);
StringBuilder sb = new StringBuilder();
sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"", Name, FileName));
sb.AppendLine("Content-Type: " + Type);
sb.AppendLine();
sw.Write(sb.ToString());
sw.Flush();
stream.Write(Content, 0, Content.Length);
stream.Position = 0;
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, (int)buffer.Length);
return buffer;
}
}
}
PostData
public class PostData
{
public PostData() { Fields = new List<IPostDataField>(); }
public List<IPostDataField> Fields { get; set; }
public Byte[] Export(out string boundary)
{
using (MemoryStream stream = new MemoryStream())
{
Random r = new Random();
string tok = "";
for (int i = 0; i < 14; i++)
tok += r.Next(10).ToString();
boundary = "---------------------------" + tok;
using (StreamWriter sw = new StreamWriter(stream))
{
//sw.WriteLine(string.Format("Content-Type: multipart/form-data; boundary=" + boundary.Replace("--", "")));
//sw.WriteLine();
//sw.Flush();
foreach (IPostDataField field in Fields)
{
sw.WriteLine("--" + boundary);
sw.Flush();
stream.Write(field.Export(), 0, (int)field.Export().Length);
}
//1 keer om het af te leren
//sw.WriteLine();
sw.WriteLine("--" + boundary + "--");
sw.Flush();
stream.Position = 0;
using (StreamReader sr = new StreamReader(stream))
{
string bla = sr.ReadToEnd();
stream.Position = 0;
Byte[] toExport = new Byte[stream.Length];
stream.Read(toExport, 0, (int)stream.Length);
return toExport;
}
}
}
}
}