public static void UploadFile(this WebRequest webRequest, Stream fileStream, string fileName, string mimeType,
string accept = null, Action<HttpWebRequest> requestFilter = null, string method = "POST")
{
var httpReq = (HttpWebRequest)webRequest;
httpReq.UserAgent = Env.ServerUserAgent;
httpReq.Method = method;
httpReq.AllowAutoRedirect = false;
httpReq.KeepAlive = false;
if (accept != null)
httpReq.Accept = accept;
if (requestFilter != null)
requestFilter(httpReq);
var boundary = "----------------------------" + DateTime.UtcNow.Ticks.ToString("x");
httpReq.ContentType = "multipart/form-data; boundary=" + boundary;
var boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
var headerTemplate = "\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\nContent-Type: {1}\r\n\r\n";
var header = string.Format(headerTemplate, fileName, mimeType);
var headerbytes = Encoding.ASCII.GetBytes(header);
httpReq.ContentLength = fileStream.Length + headerbytes.Length + boundarybytes.Length;
if (ResultsFilter != null)
{
ResultsFilter.UploadStream(httpReq, fileStream, fileName);
return;
}
using (Stream outputStream = httpReq.GetRequestStream())
{
outputStream.Write(headerbytes, 0, headerbytes.Length);
byte[] buffer = new byte[4096];
int byteCount;
while ((byteCount = fileStream.Read(buffer, 0, 4096)) > 0)
{
outputStream.Write(buffer, 0, byteCount);
}
outputStream.Write(boundarybytes, 0, boundarybytes.Length);
outputStream.Close();
}
}