This question has already been answered:
- C # post request with file and data 3 responses
I can’t upload a file to the site via POST, tried different examples, but none of them works.
My program code:
First option
WebRequest send = WebRequest.Create(@"http://site.ru/upload"); send.Method = "POST"; send.ContentType = "multipart/form-data; boundary=85645486461"; send.ContentLength = 28163; StringBuilder sendData = new StringBuilder(); using (FileStream img = new FileStream("C:\\OpenServer\\1.jpg", FileMode.Open)) { sendData.Append("filename=" + img.ToString()); } byte[] byteData = Encoding.GetEncoding(1251).GetBytes(sendData.ToString()); send.ContentLength = byteData.Length; using (Stream sendStream = send.GetRequestStream()) { sendStream.Write(byteData, 0, byteData.Length); } using (WebResponse result = send.GetResponse()) { StreamReader reader = new StreamReader(result.GetResponseStream()); //XDocument res = XDocument.Parse(reader.ReadToEnd()); //res.Save("res.xml"); } Second option
public static string XmlHttpRequest(string urlString, string xmlContent) { string response = null; HttpWebRequest httpWebRequest = null;//Declare an HTTP-specific implementation of the WebRequest class. HttpWebResponse httpWebResponse = null;//Declare an HTTP-specific implementation of the WebResponse class //Creates an HttpWebRequest for the specified URL. httpWebRequest = (HttpWebRequest)WebRequest.Create(urlString); try { byte[] bytes; bytes = System.Text.Encoding.ASCII.GetBytes(xmlContent); //Set HttpWebRequest properties httpWebRequest.Method = "POST"; httpWebRequest.ContentLength = bytes.Length; httpWebRequest.ContentType = "multipart/form-data; boundary=85645486461"; using (Stream requestStream = httpWebRequest.GetRequestStream()) { //Writes a sequence of bytes to the current stream requestStream.Write(bytes, 0, bytes.Length); requestStream.Close();//Close stream } //Sends the HttpWebRequest, and waits for a response. httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); if (httpWebResponse.StatusCode == HttpStatusCode.OK) { //Get response stream into StreamReader using (Stream responseStream = httpWebResponse.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) response = reader.ReadToEnd(); } } httpWebResponse.Close();//Close HttpWebResponse } catch (WebException we) { //TODO: Add custom exception handling throw new Exception(we.Message); } catch (Exception ex) { throw new Exception(ex.Message); } finally { httpWebResponse.Close(); //Release objects httpWebResponse = null; httpWebRequest = null; } return response; } private void button1_Click(object sender, EventArgs e) { XmlHttpRequest("http://site.ru/upload", "C:\\OpenServer\\1.jpg"); }