All pastes #1341936 Raw Edit

Anonymous

public text v1 · immutable
#1341936 ·published 2009-02-19 13:01 UTC
rendered paste body
      protected string PostImage(Stream imageStream, string uploadUrl, string fileFormName, string contentType,
            IDictionary<string, string> arguments, CookieContainer cookies, string referer)
        {
            string returnValue = "";
            try
            {
                string postData = arguments.Aggregate("?", (current, arg) => current + arg.Key + "=" + arg.Value + "&");
                Uri postUri = new Uri(uploadUrl + postData.Substring(0, postData.Length - 1));
                string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
                string postHeader = string.Format("--{0}\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\nContent-Type: {3}\n\n", boundary, fileFormName ?? "file", this.mFileName, contentType ?? "application/octet-stream");

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUri);
                request.CookieContainer = cookies;
                request.ContentType = "multipart/form-data; boundary=" + boundary;
                request.Method = "POST";
                request.UserAgent = "Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; SV1; .NET CLR 2.0.50727; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
                request.Referer = referer;

                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
                byte[] boundaryBytes = Encoding.ASCII.GetBytes("\n--" + boundary + "\n");

                request.ContentLength = postHeaderBytes.Length + imageStream.Length + boundaryBytes.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                byte[] buffer = new byte[((int)Math.Min(4096, imageStream.Length)) - 1];
                int bytesRead = 0;
                int bytesReadTotal = 0;
                while (true)
                {
                    bytesRead = imageStream.Read(buffer, 0, buffer.Length);
                    if (bytesRead == 0) break;
                    requestStream.Write(buffer, 0, bytesRead);
                    bytesReadTotal += bytesRead;
                }
                requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                WebResponse response = request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                StreamReader responseReader = new StreamReader(responseStream);
                returnValue = responseReader.ReadToEnd();
                responseStream.Close();
            }
            catch (Exception ex)
            {
                this.Errors.Add(ex.Message);
                Console.WriteLine(ex.Message);
            }
            return returnValue;
        }