Not able to read the file name from the http request header - c#

I'm not able to read the file name as well as other values that come from the client. I'm using HttpWebRequest to send Multi part data to the server. My client side code looks like so:
public string upload(string file, string url)
{
HttpWebRequest requestToServer = (HttpWebRequest)
WebRequest.Create(url);
// Define a boundary string
string boundaryString = "----";
// Turn off the buffering of data to be written, to prevent
// OutOfMemoryException when sending data
requestToServer.AllowWriteStreamBuffering = false;
// Specify that request is a HTTP post
requestToServer.Method = WebRequestMethods.Http.Post;
// Specify that the content type is a multipart request
requestToServer.ContentType
= "multipart/form-data; boundary=" + boundaryString;
// Turn off keep alive
requestToServer.KeepAlive = false;
ASCIIEncoding ascii = new ASCIIEncoding();
string boundaryStringLine = "\r\n--" + boundaryString + "\r\n";
byte[] boundaryStringLineBytes = ascii.GetBytes(boundaryStringLine);
string lastBoundaryStringLine = "\r\n--" + boundaryString + "--\r\n";
byte[] lastBoundaryStringLineBytes = ascii.GetBytes(lastBoundaryStringLine);
NameValueCollection nvc = new NameValueCollection();
nvc.Add("id", "TTR");
// Get the byte array of the myFileDescription content disposition
string myFileDescriptionContentDisposition = Java.Lang.String.Format(
"Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
"myFileDescription",
"A sample file description");
byte[] myFileDescriptionContentDispositionBytes
= ascii.GetBytes(myFileDescriptionContentDisposition);
string fileUrl = file;
// Get the byte array of the string part of the myFile content
// disposition
string myFileContentDisposition = Java.Lang.String.Format(
"Content-Disposition: form-data;name=\"{0}\"; "
+ "filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n",
"myFile", Path.GetFileName(fileUrl), Path.GetExtension(fileUrl));
byte[] myFileContentDispositionBytes =
ascii.GetBytes(myFileContentDisposition);
var name = Path.GetFileName(fileUrl);
FileInfo fileInfo = new FileInfo(fileUrl);
// Calculate the total size of the HTTP request
long totalRequestBodySize = boundaryStringLineBytes.Length * 2
+ lastBoundaryStringLineBytes.Length
+ myFileDescriptionContentDispositionBytes.Length
+ myFileContentDispositionBytes.Length
+ fileInfo.Length;
// And indicate the value as the HTTP request content length
requestToServer.ContentLength = totalRequestBodySize;
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
// Write the http request body directly to the server
using (Stream s = requestToServer.GetRequestStream())
{
//foreach (string key in nvc.Keys)
//{
// s.Write(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
// string formitem = string.Format(formdataTemplate, key, nvc[key]);
// byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
// s.Write(formitembytes, 0, formitembytes.Length);
//}
// Send the file description content disposition over to the server
s.Write(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
s.Write(myFileDescriptionContentDispositionBytes, 0,
myFileDescriptionContentDispositionBytes.Length);
// Send the file content disposition over to the server
s.Write(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
s.Write(myFileContentDispositionBytes, 0,
myFileContentDispositionBytes.Length);
// Send the file binaries over to the server, in 1024 bytes chunk
FileStream fileStream = new FileStream(fileUrl, FileMode.Open,
FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
s.Write(buffer, 0, bytesRead);
} // end while
fileStream.Close();
// Send the last part of the HTTP request body
s.Write(lastBoundaryStringLineBytes, 0, lastBoundaryStringLineBytes.Length);
WebResponse response = requestToServer.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string replyFromServer = responseReader.ReadToEnd();
return replyFromServer;
}
}
The content-disposition values that are written on the client side aren't being retrieved on the server side. On the server side, the file name is read as "{0}" and subsequently other values are read as "{1}" and "{2}".
My server side code looks like so:
public async Task<HttpResponseMessage> UploadFile()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
var httpRequest = HttpContext.Current.Request;
var id = httpRequest.Form["{0}"];
var id2 = httpRequest.Form[0];
var s = id;
var l = id2;
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
}
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
postedFile.SaveAs(filePath);
// NOTE: To store in memory use postedFile.InputStream
}
return Request.CreateResponse(HttpStatusCode.Created);
}
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
I've been stuck on this for 2 days and it's driving me crazy. I have chopped and changed my code several time but each time I have different issues. This is the closest I have come to making my code work except reading the headers properly on the server.
I will forever be grateful to the person the person who will help me out.

Your client is most likely something like Android application. You use Java.Lang.String.Format there, and syntax of java format strings is different from .NET format strings, so your {0} {1} etc placesholders are not getting expanded. To fix, just use regular .NET String.Format.

Related

Conversion of Byte to PDF using ConvertAPI

Our requirement is to convert file stored in database, array of byte to PDF using ConvertAPI. We have tried multiple options but getting different errors as mention below. Can someone please help us with function to convert Byte file format to PDF.
Error 1 - The remote server returned an error: (400) Bad Request.
using (var client = new WebClient())
{
client.Headers.Add("accept", "application/octet-stream");
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
var resultFile = client.UploadData("https://v2.convertapi.com/doc/to/pdf?Secret=**********", byteTemplate);
}
 
Error 2 - The remote server returned an error: (400) Bad Request
var requestContent = new MultipartFormDataContent();
ByteArrayContent data = new ByteArrayContent(byteTemplate, 0, byteTemplate.Count());
requestContent.Add(data, "File", "Files");
requestContent.Add(new StringContent("**********"), "Secret");
var authParam = parameters.ContainsKey("secret") ? $"Secret={parameters["secret"]}" : $"Token={parameters["token"]}";
return new HttpClient().PostAsync($"https://v2.convertapi.com/{srcFormat}/to/{dstFormat}?{authParam}", requestContent).Result;
Error 3 - Code":5001,"Message":"Conversion failed."
or
Cannot access a disposed object.
Object name: 'System.Net.Http.MultipartFormDataContent'
public static HttpResponseMessage Convert(string srcFormat, string dstFormat, Dictionary<string, string> parameters, byte[] bytetemp, MemoryStream streamTemplate)
{
var requestContent = new MultipartFormDataContent();
streamTemplate.Position = 0;
requestContent.Add(new StreamContent(streamTemplate), "File", "ABC");
foreach (var parameter in parameters)
{
if (File.Exists(parameter.Value))
{
}
else
{
requestContent.Add(new StringContent(parameter.Value), parameter.Key);
}
}
var authParam = parameters.ContainsKey("secret") ? $"Secret={parameters["secret"]}" : $"Token={parameters["token"]}";
HttpContent rescont = new HttpClient().PostAsync($"https://v2.convertapi.com/{srcFormat}/to/{dstFormat}?{authParam}", requestContent).Result.Content;
String a = rescont.ReadAsStringAsync().Result;
}
Error 4 - The remote server returned an error: (400) Bad Request.
Old Code with New URL, Working with old URL
public static byte[] CovertWordtoPdf(byte[] response)
{
byte[] bufferDocxReport;
bufferDocxReport = response;
string reportName = "reportname.doc";
#region Convert DOCX report to PDF format
WebRequest convertToPdfRequest = WebRequest.Create("https://v2.convertapi.com/docx/to/pdf?Secret=************");
convertToPdfRequest.Method = "POST";
var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", NumberFormatInfo.InvariantInfo);
convertToPdfRequest.ContentType = "multipart/form-data; boundary=" + boundary;
boundary = "--" + boundary;
using (var requestStream = convertToPdfRequest.GetRequestStream())
{
// Write the file
var buffer = Encoding.ASCII.GetBytes(boundary + Environment.NewLine);
requestStream.Write(buffer, 0, buffer.Length);
buffer = Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", "name", reportName, Environment.NewLine));
requestStream.Write(buffer, 0, buffer.Length);
buffer = Encoding.ASCII.GetBytes(string.Format("Content-Type: {0}{1}{1}", "application/octet-stream", Environment.NewLine));
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Write(bufferDocxReport, 0, bufferDocxReport.Length);
buffer = Encoding.ASCII.GetBytes(Environment.NewLine);
requestStream.Write(buffer, 0, buffer.Length);
var boundaryBuffer = Encoding.ASCII.GetBytes(boundary + "--");
requestStream.Write(boundaryBuffer, 0, boundaryBuffer.Length);
}
using (var convertToPdfResponse = convertToPdfRequest.GetResponse())
using (Stream convertToPdfResponseStream = convertToPdfResponse.GetResponseStream())
{
bufferDocxReport = ReadToEnd(convertToPdfResponseStream);
}
return bufferDocxReport;
#endregion
}
Error 5 - Code:5001,Message:"Conversion failed.
var requestContent = new MultipartFormDataContent();
streamTemplate.Position = 0;
StreamContent data = new StreamContent(streamTemplate);
requestContent.Add(data, "File", "Files");
requestContent.Add(new StringContent("************"), "Secret");
var authParam = parameters.ContainsKey("secret") ? $"Secret={parameters["secret"]}" : $"Token={parameters["token"]}";
return new HttpClient().PostAsync($"https://v2.convertapi.com/{srcFormat}/to/{dstFormat}?{authParam}", requestContent).Result;
The working solution would be
const string fileToConvert = #"C:\Projects\_temp\test1.docx";
var bytesToConvert = File.ReadAllBytes(fileToConvert);
var url = new Uri("https://v2.convertapi.com/docx/to/pdf?secret=<YourSecret>");
var content = new ByteArrayContent(bytesToConvert);
content.Headers.Add("content-type", "application/octet-stream");
content.Headers.Add("content-disposition", "attachment; filename=\"test1.docx\"");
var fileBytes = new HttpClient().PostAsync(url, content).Result.Content.ReadAsByteArrayAsync().Result;
I would like to point several important things:
We should set content-type for request to application/octet-stream
because we send plain binary data in request body.
Also content-disposition should be provided to let Rest API
endpoint to know what data is sent, in this case it is file.

Upload Excel file to web server

I was trying to upload a file to a web server through UWP c# using filestream but it always gives me an error i.e 405 method not allowed when I try to upload on http://example.com/httpdocs/content. Even for testing purpose I tried uploading on my localhost but still no luck.
Any Help?
Code :
public async Task<bool> Upload(StorageFile fileName)
{
HttpMultipartFormDataContent form = new HttpMultipartFormDataContent();
cts = new CancellationTokenSource();
using (IInputStream fileStream = await fileName.OpenSequentialReadAsync())
{
HttpStreamContent content = new HttpStreamContent(fileStream);
form.Add(content, "premier", fileName.Name);
using (HttpClient client = new HttpClient())
{
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri("http://example.com/httpdocs/content")))
{
request.Content = form;
request.Headers.TryAppendWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
HttpResponseMessage response = await client.SendRequestAsync(request).AsTask(cts.Token);
var result = response.Content.ReadAsStringAsync().GetResults();
}
}
}
return true;
}
Hye, after trying much I found this code and it works perfectly. With a little correction that the request will be now sent to an aspx page i.e. http://example.com/abc.aspx. If you wanna send high mb's of excel file data then just change 4096 in Math.Min(4096, (int)fileStream.Length) accordingly
Client Side Code-
public static async Task<string> UploadFileEx(string uploadfile, string
url, string fileFormName, string contenttype, NameValueCollection
querystring, CookieContainer cookies)
{
try
{
if ((fileFormName == null) ||
(fileFormName.Length == 0))
{
fileFormName = "file";
}
if ((contenttype == null) ||
(contenttype.Length == 0))
{
contenttype = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
string postdata;
postdata = "?";
if (querystring != null)
{
foreach (string key in querystring.Keys)
{
postdata += key + "=" + querystring.Get(key) + "&";
}
}
Uri uri = new Uri(url + postdata);
string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
webrequest.CookieContainer = cookies;
webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
webrequest.Method = "POST";
// Build up the post message header
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(fileFormName);
sb.Append("\"; filename=\"");
var sd = sb.Append(Path.GetFileName(uploadfile));
sb.Append("\"");
sb.Append("\r\n");
sb.Append("Content-Type: ");
sb.Append(contenttype);
sb.Append("\r\n");
sb.Append("\r\n");
string postHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
// Build the trailing boundary string as a byte array
// ensuring the boundary appears on a line by itself
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
FileStream fileStream = new FileStream(uploadfile, FileMode.Open, FileAccess.Read);
long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
// webrequest.ContentLength = length;
webrequest.Headers[HttpRequestHeader.ContentLength] = length.ToString();
//Stream requestStream = webrequest.GetRequestStream();
Stream requestStream = await webrequest.GetRequestStreamAsync();
// Write out our post header
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
// Write out the file contents
byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
requestStream.Write(buffer, 0, bytesRead);
// Write out the trailing boundary
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
WebResponse response = await webrequest.GetResponseAsync();
Stream s = response.GetResponseStream();
StreamReader sr = new StreamReader(s);
return sr.ReadToEnd();
}
catch (Exception e)
{
e.ToString();
}
return null;
}

no http-connection possible after occurrence of server error 503

I build a windows-mobile 6.5 application (based on cf 2.0) and have a problem with a special test case of one method. So I hope someone can give me an advice or has a helpful idea what the reason for this behaviour is...
The method is called continuous every 30 seconds from inside a thread, looks for files to be transferred via a HTTP request to a web server (jboss) and brings them on their way. The server url itself is under my control.
Everything works fine ... until I stop the web server and force an 503 server error. So far so good. But after restarting the web server, I would expect, that the next call of the transfer method will end in success - but it does not. Every further try ends in a timeout exception and I have to restart the application to make it work again.
So my question is: where is the problem, when I want to connect to an uri after an earlier try has failed with error 503? It seems, that there is something cached, but what the hell should it be?
Many thanks for every hint you have.
Juergen
public static Boolean HttpUploadFile2(string url, string file)
{
HttpWebRequest requestToServer = null;
WebResponse response = null;
try
{
Logger.writeToLogFileCom(string.Format("Uploading {0} to {1}", file, url));
requestToServer = (HttpWebRequest)WebRequest.Create(url);
requestToServer. Timeout = 40000;
string boundaryString = "----SSLBlaBla";
requestToServer.AllowWriteStreamBuffering = false;
requestToServer.Method = "POST";
requestToServer.ContentType = "multipart/form-data;
boundary=" + boundaryString;
requestToServer.KeepAlive = false;
ASCIIEncoding ascii = new ASCIIEncoding();
string boundaryStringLine = "\r\n--" + boundaryString + "\r\n";
byte[] boundaryStringLineBytes = ascii.GetBytes(boundaryStringLine);
string lastBoundaryStringLine = "\r\n--" + boundaryString + "--\r\n";
byte[] lastBoundaryStringLineBytes = ascii.GetBytes(lastBoundaryStringLine);
// Get the byte array of the myFileDescription content disposition
string myFileDescriptionContentDisposition = String.Format(
"Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
"myFileDescription",
"A sample file description");
byte[] myFileDescriptionContentDispositionBytes
= ascii.GetBytes(myFileDescriptionContentDisposition);
string fileUrl = file;
// Get the byte array of the string part of the myFile content
// disposition
string myFileContentDisposition = String.Format(
"Content-Disposition: form-data;name=\"{0}\"; "
+ "filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n",
"myFile", Path.GetFileName(fileUrl), Path.GetExtension(fileUrl));
byte[] myFileContentDispositionBytes =
ascii.GetBytes(myFileContentDisposition);
FileInfo fileInfo = new FileInfo(fileUrl);
// Calculate the total size of the HTTP request
long totalRequestBodySize = boundaryStringLineBytes.Length * 2
+ lastBoundaryStringLineBytes.Length
+ myFileDescriptionContentDispositionBytes.Length
+ myFileContentDispositionBytes.Length
+ fileInfo.Length;
// And indicate the value as the HTTP request content length
requestToServer.ContentLength = totalRequestBodySize;
// Write the http request body directly to the server
using (Stream s = requestToServer.GetRequestStream())
{
//TIMEOUT OCCURED WHEN CALLING GetRequestStream
// Send the file description content disposition over to the server
s.Write(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
s.Write(myFileDescriptionContentDispositionBytes, 0,
myFileDescriptionContentDispositionBytes.Length);
// Send the file content disposition over to the server
s.Write(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
s.Write(myFileContentDispositionBytes, 0,
myFileContentDispositionBytes.Length);
// Send the file binaries over to the server, in 1024 bytes chunk
FileStream fileStream = new FileStream(fileUrl, FileMode.Open,
FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
Logger.writeToLogFileCom("writing data...");
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
s.Write(buffer, 0, bytesRead);
} // end while
fileStream.Close();
Logger.writeToLogFileCom("... finished, File closed");
// Send the last part of the HTTP request body
s.Write(lastBoundaryStringLineBytes, 0, lastBoundaryStringLineBytes.Length);
Logger.writeToLogFileCom("... finished, File closed");
} // end using
// Grab the response from the server. WebException will be thrown
// when a HTTP OK status is not returned
Logger.writeToLogFileCom("lese Response");
response = requestToServer.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string replyFromServer = responseReader.ReadToEnd();
response.Close();
if (Regex.Split(Regex.Split(replyFromServer, "content\\:RESPONSE\"\\>")[1], "\\</span\\>")[0].Equals("OK"))
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Logger.writeToLogFileCom("Fehler im HTML Sender");
Logger.writeToLogFileCom(ex.Message);
Logger.writeToLogFileCom(ex.StackTrace);
}
finally
{
try
{
if (response != null)
{
response.Close();
}
}
catch (Exception ex) { }
}
return false;
}
I solved the problem.
I added an additional try / catch block inside the finally clause to call getResponse in every situation.
finally
{
try { response = requestToServer.GetResponse(); }
catch (Exception ex) { }
[...]

Uploading a file and a string to http then getting the response

Basically I have a server which lets you upload files but it requires login so when uploading from the client I'm making I need to send not only the file to upload but also the username and password as a string and then read the response from the server. I have tried my best but I get the error "You must write ContentLength bytes to the request stream before calling [Begin]GetResponse."
My code to upload the image:
string ImgFile = Path.GetTempFileName();
img.Save(ImgFile);
byte[] LoginBytes = ASCIIEncoding.ASCII.GetBytes("username=" + Username + "&password=" + Password);
byte[] ImageBytes = File.ReadAllBytes(ImgFile);
int ByteLen = LoginBytes.Length + ImageBytes.Length;
WebRequest ReqResponse = WebRequest.Create(url);
ReqResponse.Credentials = CredentialCache.DefaultCredentials;
ReqResponse.Proxy = WebRequest.DefaultWebProxy;
ReqResponse.Proxy.Credentials = CredentialCache.DefaultCredentials;
ReqResponse.Method = "POST";
ReqResponse.ContentType = "application/x-www-form-urlencoded";
ReqResponse.ContentLength = ByteLen;
ReqResponse.GetRequestStream().Write(LoginBytes, 0, LoginBytes.Length);
ReqResponse.GetRequestStream().Write(ImageBytes, 0, ImageBytes.Length);
string response = (new StreamReader(ReqResponse.GetResponse().GetResponseStream()).ReadToEnd());
MessageBox.Show(response);
maybe it doesn't like 2 posts? could just concat them and send them at once.
void Main()
{
byte[] login = BitConverter.GetBytes("loginstring");
byte[] img = BitConverter.GetBytes("fakeimagedataherereplacewithrealbytes");
byte[] tosend = login.Concat(img).ToArray();
using(WebRequest wr = WebRequest.Create("someurl"))
{
using (Stream rs = wr.GetRequestStream())
{
rs.Write(LoginBytes, 0, LoginBytes.Length);
//...whatever
}
}
}

Upload files from client to server programmatically

I'm working on fileupload control with a simple application which transfer file to server automatically.
I used as references those samples Setting a file to upload inside the WebBrowser component and UploadFileEx but when tested doesn't create a file on the server!
Form Code:
// simulate this form
//<form action ="http://localhost/test.php" method = POST>
//<input type = text name = uname>
//<input type = password name =passwd>
//<input type = FILE name = uploadfile>
//<input type=submit>
I found this class which post file to server using HttpWebRequest:
public static string UploadFileEx( string uploadfile, string url,
string fileFormName, string contenttype,NameValueCollection querystring,
CookieContainer cookies)
{
if( (fileFormName== null) ||
(fileFormName.Length ==0))
{
fileFormName = "file";
}
if( (contenttype== null) ||
(contenttype.Length ==0))
{
contenttype = "application/octet-stream";
}
string postdata;
postdata = "?";
if (querystring!=null)
{
foreach(string key in querystring.Keys)
{
postdata+= key +"=" + querystring.Get(key)+"&";
}
}
Uri uri = new Uri(url+postdata);
string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
webrequest.CookieContainer = cookies;
webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
webrequest.Method = "POST";
// Build up the post message header
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(fileFormName);
sb.Append("\"; filename=\"");
sb.Append(Path.GetFileName(uploadfile));
sb.Append("\"");
sb.Append("\r\n");
sb.Append("Content-Type: ");
sb.Append(contenttype);
sb.Append("\r\n");
sb.Append("\r\n");
string postHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
// Build the trailing boundary string as a byte array
// ensuring the boundary appears on a line by itself
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
FileStream fileStream = new FileStream(uploadfile, FileMode.Open, FileAccess.Read);
long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
webrequest.ContentLength = length;
Stream requestStream = webrequest.GetRequestStream();
// Write out our post header
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
// Write out the file contents
byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
int bytesRead = 0;
while ( (bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0 )
requestStream.Write(buffer, 0, bytesRead);
// Write out the trailing boundary
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
requestStream.Flush();
requestStream.Close();
WebResponse responce = webrequest.GetResponse();
Stream s = responce.GetResponseStream();
StreamReader sr = new StreamReader(s);
return sr.ReadToEnd();
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
CookieContainer cookies = new CookieContainer();
//add or use cookies
NameValueCollection querystring = new NameValueCollection();
querystring["uname"]="";
querystring["passwd"]="";
string uploadfile;// set to file to upload
uploadfile = "C:\\test.jpg";
UploadFileEx(uploadfile, "http://127.0.0.1/app/Default.aspx", "uploadfile", "image/pjpeg",
querystring, cookies);
}
in my case I want to use this class via WebBrowser control but when I send post to server the file(test.jpg) not created!
It could be a problem of permission on the folder! but when tested localy using IIS I get the same problem?
Thanks
It's a bit difficult to understand your question, so sorry if this isn't the right answer, but if you want to upload a file using a WebRequest with standard POST then it goes like this: Upload files with HTTPWebrequest (multipart/form-data)

Categories

Resources