0

I am trying to submit a XLS file using WebClient/HttpWebRequest. The webpage has got <input type="file" name="FileSubmitted">.

I tried to use the code given in post https://stackoverflow.com/a/2996904/521973, but I am getting an error "System.Net.WebException: The remote server returned an error: (500) Internal Server Error". When I expand the exception details I see "System.Net.WebExceptionStatus.ProtocolError"

The Headers I see in the browser Request Headers:

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:49504
Content-Type:multipart/form-data; boundary=----WebKitFormBoundary9ewWOMyBmk0YAhTL
Cookie:SFID=111222; SFTOKEN=ec60368c2e5799df-FC5E1D12-CD2A-CA0C-593E4F9DC26A8123
Host:secure.sampleweb.com
Origin:https://secure.sampleweb.com
Referer:https://secure.sampleweb.com/submit/submit.cfm?SFID=111222&SFTOKEN=ec60368c2e5799df-FC5E1D12-CD2A-CA0C-593E4F9DC26A8123
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36

Request Payload

------WebKitFormBoundary9ewWOMyBmk0YAhTL
Content-Disposition: form-data; name="FileSubmitted"; filename="Sample.xls"
Content-Type: application/vnd.ms-excel


------WebKitFormBoundary9ewWOMyBmk0YAhTL
Content-Disposition: form-data; name="FileSubmittedValue"

C:\filepath\Sample.xls
------WebKitFormBoundary9ewWOMyBmk0YAhTL--

Code:

        static void Main()
        {
            NameValueCollection postData = new NameValueCollection();
            postData["WebUser"] = "abc";
            postData["WebPass"] = "xyz";

            byte[] responseBytes = webClient.UploadValues(URLAuth, "POST", postData);
            string resultAuthTicket = Encoding.UTF8.GetString(responseBytes);

            CookieCollection cookies = webClient.CookieContainer.GetCookies(new Uri(URLAuth));

            string URL = "https://secure.sampleweb.com/submit/submit.cfm";
            string boundary = "----WebKitFormBoundary9ewWOMyBmk0YAhTL";
            System.Net.WebRequest webRequest = System.Net.WebRequest.Create(URL);

            string FilePath = "C:\\Sample.xls";
            HttpUploadFile(URL, FilePath, "FileSubmitted", "multipart/form-data", postData, boundary, cookies);
        }
        public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc, string boundary, CookieCollection cookies)
        {
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method = "POST";
            wr.KeepAlive = true;
            wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
            wr.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
wr.CookieContainer = new CookieContainer();
            wr.CookieContainer.Add(cookies);
            wr.Host = "secure.sampleweb.com";
            wr.Referer = String.Format("https://secure.sampleweb.com/submit/submit.cfm?SFID={0}&SFTOKEN={1}", cookies[0].Value, cookies[1].Value);
            wr.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36";

            Stream rs = wr.GetRequestStream();

            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            foreach (string key in nvc.Keys)
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);
                string formitem = string.Format(formdataTemplate, key, nvc[key]);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                rs.Write(formitembytes, 0, formitembytes.Length);
            }
            rs.Write(boundarybytes, 0, boundarybytes.Length);

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            string header = string.Format(headerTemplate, paramName, file, contentType);
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);

            FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                rs.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();

            WebResponse wresp = null;
            try
            {
                wresp = wr.GetResponse();
                Stream stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
            }
            catch (Exception ex)
            {
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
            }
            finally
            {
                wr = null;
            }
        }
Community
  • 1
  • 1
CoolArchTek
  • 3,729
  • 12
  • 47
  • 76
  • You need to set the `ContentLength`. – SLaks Dec 16 '13 at 20:45
  • As a site note: I would use `HttpClient` + `MultipartContent` – L.B Dec 16 '13 at 20:51
  • I tried to set wr.ContentLength = fileStream.Length; just before fileStream.Close() and I am getting "This property cannot be set after writing has started." – CoolArchTek Dec 16 '13 at 21:17
  • I moved the setting ContentLength before write part starts and now I am getting error "Bytes to be written to the stream exceed the Content-Length bytes size specified". – CoolArchTek Dec 16 '13 at 21:37
  • @CoolArchTek I guess you see now why you shouldn't form your request manually when there is already a library that can do it for you. (unless you know what your are doing really and need to do it that way) – L.B Dec 16 '13 at 22:16
  • @L.B I don't understand what you mean? can you please explain? – CoolArchTek Dec 16 '13 at 22:22
  • @CoolArchTek See my first comment and use `HttpClient` which supports posting *MultipartContent*. As you can see it is error prone to form such request with string operations and setting headers accordingly. (Your referenced link is just **** (say not good)) – L.B Dec 16 '13 at 22:28
  • No it is in your question. http://stackoverflow.com/a/2996904/521973 – L.B Dec 16 '13 at 22:49
  • I even tried to use the code in this link (http://stackoverflow.com/a/16123846/521973) which is using MultiPart. With this I am getting "Cannot close stream until all bytes are written" – CoolArchTek Dec 17 '13 at 16:30
  • UPDATE: I am getting 500 Internal server error and it says "The form field FileSubmitted did not contain a file" – CoolArchTek Dec 17 '13 at 17:16

0 Answers0