how to upload file via c# post request? ownCloud - c#

i`m using ownCloud (open source cloud) and i have a form to upload files
the form sending the post request to upload.php file that handle the upload.
the request have a lot of fields and need to send all info and cookie.
i need to develop a c# code to upload files to the cloud.
the best way in my opinion is to make a request similar to the request that the form does.
what do you think? any suggestions?
p.s i read the following solutions but it is not working.
Sending Files using HTTP POST in c#
http://bytes.com/topic/c-sharp/answers/268661-how-upload-file-via-c-code
Upload files with HTTPWebrequest (multipart/form-data)
thanks
here is some of the code:
the form:
<form data-upload-id='1'
id="data-upload-form"
class="file_upload_form"
action="<?php print_unescaped(OCP\Util::linkTo('files', 'ajax/upload.php')); ?>"
method="post"
enctype="multipart/form-data"
target="file_upload_target_1">
<input type="hidden" name="MAX_FILE_SIZE" id="max_upload" value="<?php p($_['uploadMaxFilesize']) ?>">
<input type="hidden" name="requesttoken" value="<?php p($_['requesttoken']) ?>" id="requesttoken">
<input type="hidden" class="max_human_file_size" value="(max <?php p($_['uploadMaxHumanFilesize']); ?>)">
<input type="hidden" name="dir" value="<?php p($_['dir']) ?>" id="dir">
<input type="file" id="file_upload_start" name='files[]'/>
</form>
This the way the request seen to me:
enter code here
Request URL:http://my-url/owncloud/index.php/apps/files/ajax/upload.php
Request Method:POST
Status Code:200 OK
Request Headersview parsed
POST /owncloud/index.php/apps/files/ajax/upload.php HTTP/1.1
Host: my-url
Connection: keep-alive
Content-Length: 730
Accept: */*
requesttoken: 0bbcd458174e76e139ad
Origin: http://my-url
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryVhC3ZFEhWXiSUZYT
Referer: http://my-url/owncloud/index.php/apps/files
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: oc_username=tal; oc_token=f24c041e992624d10cabbaa16aa6aeea; oc_remember_login=1; __utma=220528984.2016256779.1375771228.1375771228.1375862096.2; __utmz=220528984.1375771228.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); olfsk=olfsk4827894743066281; hblid=QHgh67nWTyXfpzWe6B1Tj9Z3JM0QBCfA; 510e8a1de6274=eqavm1nikkon6ush7con3o6ar6
Request Payload
------WebKitFormBoundaryVhC3ZFEhWXiSUZYT
Content-Disposition: form-data; name="MAX_FILE_SIZE"
537919488
------WebKitFormBoundaryVhC3ZFEhWXiSUZYT
Content-Disposition: form-data; name="requesttoken"
0bbcd458174e76e139ad
------WebKitFormBoundaryVhC3ZFEhWXiSUZYT
Content-Disposition: form-data; name="dir"
/
------WebKitFormBoundaryVhC3ZFEhWXiSUZYT
Content-Disposition: form-data; name="files[]"; filename="bg.png"
Content-Type: image/png
------WebKitFormBoundaryVhC3ZFEhWXiSUZYT--
Response Headersview parsed
HTTP/1.1 200 OK
Date: Sun, 08 Sep 2013 07:21:02 GMT
Server: Apache/2.2.16 (Debian)
X-Powered-By: PHP/5.3.3-7+squeeze16
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
X-Content-Type-Options: nosniff
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 132
Keep-Alive: timeout=15, max=99
Connection: Keep-Alive
Content-Type: text/plain; charset=utf-8
i tried this code
public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream rs = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, paramName, file, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
//StreamReader reader3 = new StreamReader(rs);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
MessageBox.Show((string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd())));
Debug.WriteLine(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));
}
catch(Exception ex)
{
Debug.WriteLine("Error uploading file", ex);
if(wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
}
the calling function:
NameValueCollection nvc = new NameValueCollection();
nvc.Add("id", "TTR");
nvc.Add("btn-submit-photo", "Upload");
FilesClass.HttpUploadFile("http://192.168.49.108/owncloud/index.php/apps/files/ajax/upload.php", #"C:\t.txt", "files[]", "text/plain", nvc);
the response from the server is {"data":{"message":"Authentication error"},"status":"error"}
that mean that i was rejected by upload.php
maybe i need to send the cookie?

Instead of trying to simulate a POST upload (which ownCloud makes fairly difficult due to security issues) you can use WebDAV to upload the file.
Simply send a PUT request to http://example.com/owncloud/remote.php/webdav/some/path

Related

C# Uploading image 400 bad request

I'm programmatically trying to change my account's avatar for a website (ask.fm). I emulated the same identical request the browser is sending, but everytime I call it it gives me "400 Bad-request".
What I noticed with some debugging is that the boundary if changed gives error, so it may be they are using some algorithms for it instead of a random number, else I don't get why my code is not working.
Raw request from browser:
POST http://upload5 .ask. fm/upload/api-avatar HTTP/1.1
Host: upload5 .ask. fm
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0
Accept: */*
Accept-Language: it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://ask. fm/account/settings/profile
Content-Length: 305167
Content-Type: multipart/form-data; boundary=---------------------------22412596920869
Origin: http://ask. fm
DNT: 1
Connection: keep-alive
-----------------------------22412596920869
Content-Disposition: form-data; name="file"; filename="1.png"
Content-Type: image/png
<...image bytes...>
-----------------------------22412596920869
Content-Disposition: form-data; name="specs"
U2FsdGVkX18XLeEmxsI+tytSpHcAV/UrBO8wmsoYERnL59rHGwF5Yz5QOeVl3GHap3ufLDGLyWxU4cCt28kPaSPq/iOusnVqRiYyp1nDD8VSvSLWa+Ndg8/TjKgaMqCgDNOrOSOPmxcV2kNPdDXNNvnuLWljYhPlBxrMGR2UeoqLNpJwsZCvs1UvVWcZFDy9SizVAOBDl6f1AIyqdvWiwjYGvg7jZ5q6ykTZda1pYuk=
-----------------------------22412596920869
Content-Disposition: form-data; name="ts"
1472985276554
-----------------------------22412596920869--
Raw request from my application:
POST http://upload5 .ask. fm/upload/api-avatar HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0
Accept: */*
Accept-Language: it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://ask. fm/account/settings/profile
Origin: http://ask. fm
DNT: 1
Content-Type: multipart/form-data; boundary=-----------------------------680184
Host: upload5 .ask. fm
Content-Length: 305133
-----------------------------680184
Content-Disposition: form-data; name="file"; filename="1.png"
Content-Type: image/png
<...image bytes...>
-----------------------------680184
Content-Disposition: form-data; name="specs"
U2FsdGVkX19t+38KPvBBtpXmUUu8QGk61dKTvb0hEGZE165ot7tahOd1VZ1+uXbeGqy/GFM2uJ9Q/MTkStYZ4gITWc3/davB3NKJVcJN7xQR5/pNPMspR7PgCU2UhgWNFQuVHPhp9fiokIaR+QyqAOtQdd0nd6oFAIsKRPIBDjooo1sKE4BaXDHdQibNSBEdeJRgv1DjwtX77wEtXoV8DvS3+Z0sH2FJeY+iAY2bB2Q=
-----------------------------680184
Content-Disposition: form-data; name="ts"
1472985387451
-----------------------------680184--
So it's almost identical except the fact that there's no Keep-alive, I don't know why considering it's written in my request.
However, this is my code:
string Html = GetHtml("http://ask. fm/account/settings/profile");
string specs = Utils.GetSpecs(Html);
string ts = Utils.GetTs(Html);
Bitmap Image = new Bitmap(ImagePath);
MemoryStream mStream = new MemoryStream();
Image.Save(mStream, ImageFormat.Jpeg);
byte[] Bytes = mStream.ToArray();
string Boundary = "-----------------------------" + rnd.Next(100000, 900000);
string HeaderTemplate = #"Content-Disposition: form-data; name=""file""; filename=""1.png""\r\nContent-Type: ""image/png""\r\n\r\n";
HttpWebRequest postReq = (HttpWebRequest)WebRequest.Create("http://upload5 .ask.fm/upload/api-avatar");
postReq.AutomaticDecompression = DecompressionMethods.GZip;
WebHeaderCollection postHeaders = postReq.Headers;
postReq.Method = "POST";
postReq.Host = "upload5 .ask.fm";
postReq.ServicePoint.Expect100Continue = false;
postReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0";
postReq.Accept = "*/*";
postHeaders.Add("Accept-Language", "it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3");
postHeaders.Add("Accept-Encoding", "gzip, deflate");
postReq.Referer = "http://ask .fm/account/settings/profile";
postHeaders.Add("Origin", "http://ask .fm");
postHeaders.Add("DNT", "1");
postReq.ContentType = "multipart/form-data; boundary=" + Boundary;
postReq.CookieContainer = Cookies;
postReq.KeepAlive = true;
string BoundaryHeader = Boundary + Environment.NewLine + #"Content-Disposition: form-data; name=""file""; filename=""{0}""" + Environment.NewLine + "Content-Type: image/png" + Environment.NewLine + Environment.NewLine;
string BoundaryEnd = Environment.NewLine + Boundary + Environment.NewLine + #"Content-Disposition: form-data; name=""specs""" + Environment.NewLine + Environment.NewLine + "{0}" + Environment.NewLine + Boundary + Environment.NewLine + #"Content-Disposition: form-data; name=""ts""" + Environment.NewLine + Environment.NewLine + "{1}" + Environment.NewLine + Boundary + "--";
byte[] BoundaryHeaderBytes = Encoding.UTF8.GetBytes(string.Format(BoundaryHeader, Path.GetFileName(ImagePath)));
byte[] BoundaryEndBytes = Encoding.ASCII.GetBytes(string.Format(BoundaryEnd, specs, ts));
FileStream fileStream = new FileStream(ImagePath, FileMode.Open, FileAccess.Read);
long length = BoundaryHeaderBytes.Length + fileStream.Length + BoundaryEndBytes.Length;
postReq.ContentLength = length;
Stream requestStream = postReq.GetRequestStream();
requestStream.Write(BoundaryHeaderBytes, 0, BoundaryHeaderBytes.Length);
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);
requestStream.Write(BoundaryEndBytes, 0, BoundaryEndBytes.Length);
WebResponse responce = postReq.GetResponse();
Stream s = responce.GetResponseStream();
StreamReader sr = new StreamReader(s);
What could the problem be? It's been some day since I'm struggling with this and I didn't find a solution yet, thank you in advance for any answers!

Unable to upload file using HTTP POST

I'm trying to upload a file using HTTP Post but somehow there is no file to be found when I process the request on the server side. I was able to create a similar request and successfully upload file using Chrome's Postman extension, but somehow can't do the same programmatically.
Client code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fullUrl);
request.Method = "POST";
using (Stream requestStream = request.GetRequestStream())
{
string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
byte[] trailer = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n";
string header = string.Format(headerTemplate, "Files", "myFile.xml", "text/xml");
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
requestStream.Write(boundarybytes, 0, boundarybytes.Length);
requestStream.Write(headerbytes, 0, headerbytes.Length);
requestStream.Write(uploadedFile, 0, uploadedFile.Length);
requestStream.Write(trailer, 0, trailer.Length);
}
The request looks like this (in Fiddler) :
POST https://host/myUrl
Content-Length: 1067
Expect: 100-continue
Connection: Keep-Alive
------------8d2942f79ab208e
Content-Disposition: form-data; name="Files"; filename="myFile.xml"
Content-Type:text/xml
<myFile>
Something
</myFile>
------------8d2942f79ab208e
Server side:
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count != 1)
return BadRequest("Didn't get the file.");
But I always get httpRequest.Files.Count to be zero. Why?
The following request (created using Postman) gives me httpRequest.Files.Count to be one, as expected.
POST myUrl HTTP/1.1
Host: host
Cache-Control: no-cache
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="Files"; filename="myFile.xml"
Content-Type: text/xml
----WebKitFormBoundaryE19zNvXGzXaLvS5C
What am I doing wrong?
Figured it out. Thanks to this blog
Made two changes:
1) Added ContentType :
request.ContentType = "multipart/form-data; boundary=" + boundary;
2) Modified how the boundary ends
byte[] trailer = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "--");
And it works now. Hope this helps someone.
Perhaps you need to set the request's content type to "multipart/form-data"
request.ContentType = "multipart/form-data";

using HttpWebRequest upload file (multipart/form-data)

I was trying to upload file to web server through API but i got error
"The remote server returned an error: (403) Forbidden." I also try upload file via postman and it was successful.Below my code uploading file and postman preview.
public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
{
MessageBox.Show(string.Format("Uploading {0} to {1}", file, url));
var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
var boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
var wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = CredentialCache.DefaultCredentials;
var rs = wr.GetRequestStream();
const string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
var formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
const string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
var header = string.Format(headerTemplate, paramName, file, contentType);
var headerbytes = Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
var buffer = new byte[4096];
var bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
var trailer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
var stream2 = wresp.GetResponseStream();
var reader2 = new StreamReader(stream2);
MessageBox.Show(string.Format("Response is: {0}", reader2.ReadToEnd()));
}
catch (Exception ex)
{
MessageBox.Show("Error uploading file" + ex);
if (wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
}
this is postman preview
POST / HTTP/1.1
Host: buckname.s3.amazonaws.com
Cache-Control: no-cache
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="key"
2014/6b9830b098c9871c6356a5e55af91bfd/${filename}
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="AWSAccessKeyId"
AKIAJNXK6LUBUSZBXJIQ
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="acl"
public-read
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="policy"
eyJleHBpcmF0aW9uIjoiMjAxNC0wOC0yMlQxMDo1MTow
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="signature"
ezYsOF/P6bGcOqQdyJeE7iApu2A=
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="success_action_status"
201
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="secure"
true
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="x-amz-storage-class"
REDUCED_REDUNDANCY
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="file"; filename="exp.png"
Content-Type: image/png
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="Content-Type"
image/jpeg
----WebKitFormBoundaryE19zNvXGzXaLvS5C
edit (code sending)
var nvc = new NameValueCollection
{
{"AWSAccessKeyId", fields.AWSAccessKeyId},
{"Content-Type", "image/jpeg"},
{"acl", fields.acl},
{"key", fields.key},
{"policy", fields.policy},
{"secure", secure.ToString()},
{"signature", signature},
{"success_action_status", fields.success_action_status},
{"x-amz-storage-class", "REDUCED_REDUNDANCY"}
};
HttpUploadHelper.HttpUploadFile(responsFieldsDeSerial.url.ToString(),#"C:\1.png", "file", "image/jpeg",nvc);
thank you!
My error was
<?xml version="1.0" encoding="UTF-8"?> <Error><Code>AccessDenied</Code><Message>Invalid according to Policy: Policy Condition failed: ["eq", "$Secure", "true"]</Message>
Problem was value of field (in my case : secure) case senstive i tried to post True but it must be true.

C# CF Post Request | Internal server error 500

I want to keep it as simple as possible -
-We switched from an Godaddy windows hosting to Godaddy linux hosting
-After switching i get internal server error 500 when iam using POST from an c#
program(compact framework) with the content type - multipartformdata,
However i can still use a normal html form that sits on the server to post with no issues.
-Everything worked absolutly fine before the switch! I can still do GET requests,
and even normal(Not multipart/form-data) POST request from my C# app .
Headers and content from the request / response using the code below :
Request headers -
POST /users/test.php HTTP/1.1
Content-Type: multipart/form-data; boundary=----------------------------8d0cb969d25c418
Host: mydomain(i censor)
Content-Length: 403
Expect: 100-continue
Connection: Keep-Alive
Request content -
------------------------------8d0cb969d25c418
Content-Disposition: form-data; name="title";
test
------------------------------8d0cb969d25c418
Content-Disposition: form-data; name="pwd";
testpwd
------------------------------8d0cb969d25c418
Content-Disposition: form-data; name="file"; filename=test.txt
Content-Type: text/html
testfile
------------------------------8d0cb969d25c418
Response headers -
HTTP/1.1 500 Internal Server Error
Date: Fri, 20 Dec 2013 10:32:01 GMT
Server: Apache mod_fcgid/2.3.10-dev
Content-Length: 662
Keep-Alive: timeout=5
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1
This is my C# Code(Note - I must use compact framework only) :
openFileDialog1.ShowDialog();
NameValueCollection formsdata = new NameValueCollection();
formsdata.Add("title", textBox3.Text);
formsdata.Add("pwd", textBox4.Text);
string[] names = new string[1] { openFileDialog1.FileName };
UploadFilesToRemoteUrl("http://mydomain/users/writefile.php", names, "notused", formsdata, openFileDialog1.SafeFileName);
and for the method UploadFilesToRemoteUrl -
public static void UploadFilesToRemoteUrl(string url, string[] files, string
logpath, NameValueCollection nvc, string filename)
{
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=" + filename + "\r\n Content-Type: text/html\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, "file", 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;
}
Any help is really highly appreciated!

PHP can't get raw data sent as multipart/form-data

This is client code (C#) :
string boundary = "--ABC";
try
{
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "multipart/form-data;boundary="+boundary;
using (var requestStream = request.GetRequestStream())
using (var writer = new StreamWriter(requestStream))
{
writer.WriteLine(boundary);
writer.WriteLine("Content-Disposition: form-data; name=\"data\"");
writer.WriteLine();
writer.WriteLine("abcdefg");
writer.WriteLine(boundary + "--");
writer.Flush();
}
string responseData = string.Empty;
using (var response = request.GetResponse())
using (var responseStream = response.GetResponseStream())
using (var reader = new StreamReader(responseStream))
{
responseData=reader.ReadToEnd();
}
and this is the server code (php):
print file_get_contents("php://input");
or:
print $_POST["data"];
or:
print $http_raw_post_data;
or:
$fp=fopen("php://output","rb");
$contents=fread($fp,5);
fclose($fp);
print $contents;
Non of these code working, all print empty.
Could any one help please?
The following example illustrates "multipart/form-data" encoding. Suppose we have the following form:
<FORM action="http://server.com/cgi/handle"
enctype="multipart/form-data"
method="post">
<P>
What is your name? <INPUT type="text" name="submit-name"><BR>
What files are you sending? <INPUT type="file" name="files"><BR>
<INPUT type="submit" value="Send"> <INPUT type="reset">
</FORM>
If the user enters "Larry" in the text input, and selects the text file "file1.txt", the user agent might send back the following data:
Content-Type: multipart/form-data; boundary=AaB03x
--AaB03x
Content-Disposition: form-data; name="submit-name"
Larry
--AaB03x
Content-Disposition: form-data; name="files"; filename="file1.txt"
Content-Type: text/plain
... contents of file1.txt ...
--AaB03x--
If the user selected a second (image) file "file2.gif", the user agent might construct the parts as follows:
Content-Type: multipart/form-data; boundary=AaB03x
--AaB03x
Content-Disposition: form-data; name="submit-name"
Larry
--AaB03x
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=BbC04y
--BbC04y
Content-Disposition: file; filename="file1.txt"
Content-Type: text/plain
... contents of file1.txt ...
--BbC04y
Content-Disposition: file; filename="file2.gif"
Content-Type: image/gif
Content-Transfer-Encoding: binary
...contents of file2.gif...
--BbC04y--
--AaB03x--
Multipart Form Post in C# Example
TRY THIS:
string boundary = "AaB03x";
try
{
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "multipart/form-data;boundary="+boundary;
using (var requestStream = request.GetRequestStream())
using (var writer = new StreamWriter(requestStream))
{
writer.WriteLine("--"+boundary);
writer.WriteLine( "Content-Disposition: form-data; name=\"files\"; filename=\"file1.txt\"");
writer.WriteLine("Content-Type: text/plain
");
writer.WriteLine("example");
writer.WriteLine("--"boundary + "--");
writer.Flush();
}
string responseData = string.Empty;
using (var response = request.GetResponse())
using (var responseStream = response.GetResponseStream())
using (var reader = new StreamReader(responseStream))
{
responseData=reader.ReadToEnd();
}

Categories

Resources