I have a small C# web application.How can I get the c# code that allows user to send files by HTTP POST.It should be able to send text files,image files,excel, csv, doc (all types of files) without using stream reader and all.
Asked
Active
Viewed 6.2k times
23
-
http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data – Ravi Gadag Apr 01 '13 at 06:44
-
2`I have tried different methods but none of them helped me.` - if you showed some of the methods you have tried we might be able to see what is wrong with them. Right now, it's hard to have a constructive discussion. – Darin Dimitrov Apr 01 '13 at 06:44
-
1Duplicate of [Send a file via HTTP POST with C#](http://stackoverflow.com/questions/1131425/send-a-file-via-http-post-with-c-sharp) and various others. Show what you have tried, and upvoters, please consider whether a question you're upvoting is a welcome addition to the site or just a duplicate. – CodeCaster Apr 01 '13 at 07:36
3 Answers
16
You can try the following code:
public void PostMultipleFiles(string url, string[] files)
{
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest.Method = "POST";
httpWebRequest.KeepAlive = true;
httpWebRequest.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}";
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
memStream.Write(boundarybytes, 0, boundarybytes.Length);
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();
}
httpWebRequest.ContentLength = memStream.Length;
Stream requestStream = httpWebRequest.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();
try
{
WebResponse webResponse = httpWebRequest.GetResponse();
Stream stream = webResponse.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string var = reader.ReadToEnd();
}
catch (Exception ex)
{
response.InnerHtml = ex.Message;
}
httpWebRequest = null;
}

Bisileesh
- 1,982
- 2
- 19
- 29
-
21Just dumping 50 lines of code is not an answer. There are many answers to this question and many of this code is (more error-proof too) already built in in .NET types, like the WebClient and HttpClient. – CodeCaster Apr 01 '13 at 07:43
-
-
1could you give an example of the url .. does it contain the file name ? – eran otzap Jul 26 '16 at 14:58
10
Using .NET 4.5 (or .NET 4.0 by adding the Microsoft.Net.Http package from NuGet) there is an easier way to simulate form requests. Here is an example:
private System.IO.Stream Upload(string actionUrl, string paramString, Stream paramFileStream, byte [] paramFileBytes)
{
HttpContent stringContent = new StringContent(paramString);
HttpContent fileStreamContent = new StreamContent(paramFileStream);
HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(stringContent, "param1", "param1");
formData.Add(fileStreamContent, "file1", "file1");
formData.Add(bytesContent, "file2", "file2");
var response = client.PostAsync(actionUrl, formData).Result;
if (!response.IsSuccessStatusCode)
{
return null;
}
return response.Content.ReadAsStreamAsync().Result;
}
}

Joshcodes
- 8,513
- 5
- 40
- 47
9
try this
string fileToUpload = @"c:\user\test.txt";
string url = "http://example.com/upload";
using (var client = new WebClient())
{
byte[] result = client.UploadFile(url, fileToUpload);
string responseAsString = Encoding.Default.GetString(result);
}