This question has already been answered:

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"); } 

Reported as a duplicate by PashaPash member c # May 31 '16 at 9:01 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

2 answers 2

Try this

 // Получаем путь к файл var filePath = jQuery('#fileID').prop("files")[0]; // Создаем FormData объект var formData = new FormData(); formData.append('file', filePath ); //Можно отправить еще кое что если необходимо formData.append('value', 'key' ); // Отпровляем файл jQuery.ajax({ type: 'POST', url: 'здесь адрес на который загружашь файл', // Вставь ссылку data: formData, dataType: "JSON", // Ожидаеться ответ в виде JSON cache: false, contentType: false, processData: false, success: function( data ) { console.log( 'Success' ); }, error: function( data ) { console.log( 'ERROR: output error data' ); console.log( data ); } }); 
  • The program is written in c #, and js on the site handles file upload, an example is needed on Sharpe - edvardpotter

Found a great solution.

 public static void UploadFilesToRemoteUrl(string url, string[] files,string logpath, NameValueCollection nvc) { long length = 0; string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url); httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary; httpWebRequest2.Method = "POST"; httpWebRequest2.KeepAlive = true; httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials; Stream memStream = new System.IO.MemoryStream(); byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}"; foreach (string key in nvc.Keys) { string formitem = string.Format(formdataTemplate, key, nvc[key]); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); memStream.Write(formitembytes, 0, formitembytes.Length); } memStream.Write(boundarybytes, 0, boundarybytes.Length); string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n"; for (int i = 0; i < files.Length; i++) { //string header = string.Format(headerTemplate, "file" + i, files[i]); string header = string.Format(headerTemplate, "uplTheFile", files[i]); byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header); memStream.Write(headerbytes, 0, headerbytes.Length); FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { memStream.Write(buffer, 0, bytesRead); } memStream.Write(boundarybytes, 0, boundarybytes.Length); fileStream.Close(); } httpWebRequest2.ContentLength = memStream.Length; Stream requestStream = httpWebRequest2.GetRequestStream(); memStream.Position = 0; byte[] tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); requestStream.Write(tempBuffer, 0, tempBuffer.Length); requestStream.Close(); WebResponse webResponse2 = httpWebRequest2.GetResponse(); Stream stream2 = webResponse2.GetResponseStream(); StreamReader reader2 = new StreamReader(stream2); MessageBox.Show(reader2.ReadToEnd()); webResponse2.Close(); httpWebRequest2 = null; webResponse2 = null; } 

Used the same way:

 NameValueCollection nvc = new NameValueCollection(); HttpUploadFile("http://site.ru/upload", @"C:\\OpenServer\\1.jpg", "upload", "image/jpeg", nvc);