Note that there are some explanatory texts on larger screens.

plurals
  1. POWebRequest POST with both file and parameters
    text
    copied!<p>I'm trying to upload a file and a send along a few parameters to my site using .NET / C#. Having read a few tutorials that do either a few parameters or a file, I've tried, unsuccessfully, to combine them. Here is how I try doing it:</p> <pre><code>WebRequest req = WebRequest.Create(baseURL + "upload"); req.Credentials = new NetworkCredential(username, password); String boundary = "B0unD-Ary"; req.ContentType = "multipart/form-data; boundary=" + boundary; req.Method = "POST"; ((HttpWebRequest)req).UserAgent = "UploadTester v0.1"; string postData = "--" + boundary + "\nContent-Disposition: form-data\n"; postData += "myId=123&amp;someFk=456"; postData += "\n--" + boundary + "\nContent-Disposition: form-data; name=\"file\" filename=\"upload.pdf\" Content-Type: application/pdf\n\n"; byte[] byteArray = Encoding.UTF8.GetBytes(postData); byte[] filedata = null; using (BinaryReader reader = new BinaryReader(File.OpenRead("myfile.pdf"))) filedata = reader.ReadBytes((int)reader.BaseStream.Length); req.ContentLength = byteArray.Length + filedata.Length; req.GetRequestStream().Write(byteArray, 0, byteArray.Length); req.GetRequestStream().Write(filedata, 0, filedata.Length); WebResponse response = req.GetResponse(); Stream data = response.GetResponseStream(); StreamReader sReader = new StreamReader(data); String sResponse = sReader.ReadToEnd(); response.Close(); </code></pre> <p>When I execute it, I get a 500 exception, saying "Header section has more than 10240 bnytes (maybe it is not properly terminated)" and Wireshark informs me that the request sent was a malformed package, where the MIME multipart was malformed.</p> <p>There are probably several issues here, so please let me know all the problems you can spot</p> <p><strong>Update</strong>: to separate MIME from C#/.NET, I've spawned a thread here: <a href="https://stackoverflow.com/questions/1880002/error-in-mime-packet-for-http-post">https://stackoverflow.com/questions/1880002/error-in-mime-packet-for-http-post</a></p> <p><strong>Update 2</strong>: So the backend indeed has issues with the content-length, saying that the amount of bytes available for reading is smaller than the stated content-length. BUT! If I reduce the content-length in req.ContentLength accordingly, I don't have a buffer size large enough for sending the data. Any suggestions?</p> <p><strong>Update 3</strong>: Actually, it looks like the header has a too large size compared to how much data it contains</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload