I am trying to use the ImageShack API to upload images. To use it, I am supposed to POST the image using multipart/form-data. I did it like ...
var postData = "";
var req = HttpWebRequest.Create("http://www.imageshack.us/upload_api.php");
req.Method = "POST";
req.ContentType = "multipart/form-data";
postData += "key=my_key_here&";
postData += "type=base64&";
// get base64 data from image
byte[] bytes = File.ReadAllBytes(#"D:\tmp\WpfApplication1\WpfApplication1\Images\Icon128.gif");
string encoded = Convert.ToBase64String(bytes);
postData += "fileupload=" + encoded;
byte[] reqData = Encoding.UTF8.GetBytes(postData);
using (Stream dataStream = req.GetRequestStream())
{
dataStream.Write(reqData, 0, reqData.Length);
}
var res = (HttpWebResponse)req.GetResponse();
var resStream = res.GetResponseStream();
var reader = new StreamReader(resStream);
string resString = reader.ReadToEnd();
txt1.Text = resString;
but ImageShack is complaining that
<links>
<error id="parameter_missing">Sorry, but we've detected that unexpected data is received. Required parameter 'fileupload' is missing or your post is not multipart/form-data</error>
</links>
FileUpload is present and I am using multipart/form-data whats wrong?
UPDATE:
New Code http://pastebin.com/TN6e0CD8
Post data http://pastebin.com/fYE9fsxs
UPDATE 2
i looked at the other question Multipart forms from C# client. modified my code with boundary, removed the expect 100 header still i cant get it working ...
ServicePointManager.Expect100Continue = false;
var boundary = "-----------------------------28520690214962";
var newLine = Environment.NewLine;
var propFormat = boundary + newLine +
"Content-Disposition: form-data; name=\"{0}\"" + newLine + newLine +
"{1}" + newLine + newLine;
var fileHeaderFormat = boundary + newLine +
"Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + newLine;
var req = (HttpWebRequest)HttpWebRequest.Create("http://jm/php/upload.php");
req.Method = WebRequestMethods.Http.Post;
req.ContentType = "multipart/form-data; boundary=" + boundary;
using (var reqStream = req.GetRequestStream()) {
var reqWriter = new StreamWriter(reqStream);
var tmp = string.Format(propFormat, "str1", "hello world");
reqWriter.Write(tmp);
tmp = string.Format(propFormat, "str2", "hello world 2");
reqWriter.Write(tmp);
reqWriter.Write(boundary + "--");
reqWriter.Flush();
}
var res = req.GetResponse();
using (var resStream = res.GetResponseStream()) {
var reader = new StreamReader(resStream);
txt1.Text = reader.ReadToEnd();
}
I finally got it with the following code ...
var boundary = "------------------------" + DateTime.Now.Ticks;
var newLine = Environment.NewLine;
var propFormat = "--" + boundary + newLine +
"Content-Disposition: form-data; name=\"{0}\"" + newLine + newLine +
"{1}" + newLine;
var fileHeaderFormat = "--" + boundary + newLine +
"Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + newLine;
var req = (HttpWebRequest)HttpWebRequest.Create("http://jm/php/upload.php");
req.Method = WebRequestMethods.Http.Post;
req.ContentType = "multipart/form-data; boundary=" + boundary;
using (var reqStream = req.GetRequestStream()) {
var reqWriter = new StreamWriter(reqStream);
var tmp = string.Format(propFormat, "str1", "hello world");
reqWriter.Write(tmp);
tmp = string.Format(propFormat, "str2", "hello world 2");
reqWriter.Write(tmp);
reqWriter.Write("--" + boundary + "--");
reqWriter.Flush();
}
var res = req.GetResponse();
using (var resStream = res.GetResponseStream()) {
var reader = new StreamReader(resStream);
txt1.Text = reader.ReadToEnd();
}
Notice boundaries have to begin with -- {boundary declared in ContentType} and ending boundary must begin & end with -- . in my case, I originally used
var propFormat = boundary + newLine +
"Content-Disposition: form-data; name=\"{0}\"" + newLine + newLine +
"{1}" + newLine;
replace it with
var propFormat = "--" + boundary + newLine +
"Content-Disposition: form-data; name=\"{0}\"" + newLine + newLine +
"{1}" + newLine;
and everything works
I believe that you are not building the request body correctly.
First, you need to include part boundary (random text) in content type header. For example,
Content-Type: multipart/form-data;
boundary=----WebKitFormBoundarySkAQdHysJKel8YBM
Now format of request body will be something like
------WebKitFormBoundarySkAQdHysJKel8YBM
Content-Disposition: form-data;name="key"
KeyValueGoesHere
------WebKitFormBoundarySkAQdHysJKel8YBM
Content-Disposition: form-data;name="param2"
ValueHere
------WebKitFormBoundarySkAQdHysJKel8YBM
Content-Disposition: form-data;name="fileUpload"; filename="y1.jpg"
Content-Type: image/jpeg
[image data goes here]
I will suggest you to use tool such as Fiddler to understand how these requests are built.
This is nothing like multipart/form-data
There's no boundaries between fields (needed even with one field).
Why are you base-64 encoding?
There's no indication of the content-type of the image.
Take a look at RFC 2388 for the actual format spec. It can also be useful to look at a Fiddler grab of a file upload from a web-page.
Related
Here Upload pdf via multipart-HTML-Post does change file I created some code for uploading a pdf with a multipart-HTML-Post in vba.
This is the code I use:
Public Function sap_addTest(ByVal par_objectID As String, ByVal par_description As String, ByVal par_filename As String) As Integer
Dim ls_param As String
Dim text As String
Dim line As String
Dim url As String
Dim web As MSXML2.XMLHTTP60
url = "http://someurl.xml"
Set web = CreateObject("MSXML2.XMLHTTP")
Call web.Open("POST", url, False)
Const Boundary As String = "AaB03x"
Call web.setRequestHeader("content-type", "multipart/form-data;boundary=" & Boundary)
Call web.setRequestHeader("ws-callingapplication", sys_db)
Call web.setRequestHeader("Connection", "Keep-Alive")
Call web.setRequestHeader("cache-control", "no-cache")
Dim baBuffer() As Byte
Dim bytData
Dim bytPayLoad
With CreateObject("ADODB.Stream")
.Type = 1
.Mode = 3
.Open
.LoadFromFile par_filename
bytData = .Read
End With
With CreateObject("ADODB.Stream")
.Mode = 3
.Charset = "Windows-1252"
.Open
.Type = 2
.WriteText vbNewLine & "--" & Boundary & vbNewLine & "Content-Disposition: form-data; name=""object_id""" & vbNewLine & vbNewLine & par_objectID
.WriteText vbNewLine & "--" & Boundary & vbNewLine & "Content-Disposition: form-data; name=""description""" & vbNewLine & vbNewLine & par_description
.WriteText vbNewLine & "--" & Boundary & vbNewLine & "Content-Disposition: form-data; name=""file""; filename=""" & par_filename & """" & vbNewLine
.WriteText vbNewLine
.Position = 0
.Type = 1
.Position = .Size
.Write bytData
.Position = 0
.Type = 2
.Position = .Size
.WriteText vbNewLine & vbNewLine & "--" & Boundary & "--" & vbNewLine
.Position = 0
.Type = 1
bytPayLoad = .Read
End With
Call web.Send(bytPayLoad)
'Debug.Print web.status
'Debug.Print web.responseText
End Function
But now I have to do the same thing in C#. I probably use HttpWebRequest instead of XMLHTTP. But my problem is how to replace the ADODB.Stream? System.IO.Stream does not seem to have the functions/properties I use (Mode, Type, WriteText, charset). This is the code I use right now:
public void Upload(ICommandLineInfo info)
{
var webRequest = HttpWebRequest.Create(info.Url) as HttpWebRequest;
const string HTTPBoundary = "AaB03x";
webRequest.ContentType = "multipart/form-data;boundary=" + HTTPBoundary;
const string HTTPHeaderCallingApplicationName = "ws-callingapplication";
webRequest.Headers.Add(HTTPHeaderCallingApplicationName, info.CallingApplication);
webRequest.KeepAlive = true;
const string HTTPHeaderCacheControlName = "cache-control";
const string HTTPHeaderValueCacheControlNo = "no-cache";
webRequest.Headers.Add(HTTPHeaderCacheControlName, HTTPHeaderValueCacheControlNo);
webRequest.Method = "POST";
using (Stream requestStream = webRequest.GetRequestStream())
{
//Here I dont know how to write my file into the Request stream
//requestStream.Write(bytes, 0, bytes.Length); ?
requestStream.Close();
}
var response = (HttpWebResponse)webRequest.GetResponse();
}
I found this multipart post -- uploading a file to, but the code is Java and there are several pieces missing in C# (like HttpPost, MultipartEntityBuilder and so on)
So how to build the byte array for the request stream?
Update:
This is the code I use currently:
public void Upload(ICommandLineInfo info)
{
var webRequest = HttpWebRequest.Create(info.Url) as HttpWebRequest;
const string HTTPBoundary = "AaB03x";
webRequest.ContentType = "multipart/form-data;boundary=" + HTTPBoundary;
const string HTTPHeaderCallingApplicationName = "ws-callingapplication";
webRequest.Headers.Add(HTTPHeaderCallingApplicationName, info.CallingApplication);
webRequest.KeepAlive = true;
webRequest.UseDefaultCredentials = true;
webRequest.PreAuthenticate = true;
webRequest.Credentials = CredentialCache.DefaultCredentials;
const string HTTPHeaderCacheControlName = "cache-control";
const string HTTPHeaderValueCacheControlNo = "no-cache";
webRequest.Headers.Add(HTTPHeaderCacheControlName, HTTPHeaderValueCacheControlNo);
webRequest.Method = "POST";
Stream requestStream = webRequest.GetRequestStream();
string stringInfo = "";
stringInfo = stringInfo + Environment.NewLine + "--" + HTTPBoundary + Environment.NewLine + "Content-Disposition: form-data; name=\"itemName\"" + Environment.NewLine + Path.GetFileName(info.Filename);
stringInfo = stringInfo + Environment.NewLine + "--" + HTTPBoundary + Environment.NewLine + "Content-Disposition: form-data; name=\"parentNickname\"" + Environment.NewLine + info.ParentNickname;
stringInfo = stringInfo + Environment.NewLine + "--" + HTTPBoundary + Environment.NewLine + "Content-Disposition: form-data; name=\"file\"; filename=\"" + info.Filename + "\"" + Environment.NewLine + Environment.NewLine;
var stringBytes = Encoding.ASCII.GetBytes(stringInfo);
requestStream.Write(stringBytes, 0, stringBytes.Length);
var fileBytes = File.ReadAllBytes(info.Filename);
requestStream.Write(stringBytes, 0, stringBytes.Length);
string endInfo = Environment.NewLine+ Environment.NewLine + "--" + HTTPBoundary + "--" + Environment.NewLine;
var endBytes = Encoding.ASCII.GetBytes(endInfo);
requestStream.Write(endBytes, 0, endBytes.Length);
requestStream.Flush();
requestStream.Close();
var response = (HttpWebResponse)webRequest.GetResponse();
}
unfortunately webRequest.GetResponse() throws an exception:
The remoteserver returned an error. 500: Internal server error
My college - who is responsible for the serverpart - tells me that he gets an "unexpected end of stream"-error.
It seems like there is a ADODB Stream in c# also. In the Reference: "ADODB". So my final Code lookes like this:
public void Upload(ICommandLineInfo info)
{
var webRequest = HttpWebRequest.Create(info.Url) as HttpWebRequest;
const string HTTPBoundary = "AaB03x";
webRequest.ContentType = "multipart/form-data;boundary=" + HTTPBoundary;
const string HTTPHeaderCallingApplicationName = "ws-callingapplication";
webRequest.Headers.Add(HTTPHeaderCallingApplicationName, info.CallingApplication);
webRequest.KeepAlive = true;
webRequest.UseDefaultCredentials = true;
webRequest.PreAuthenticate = true;
webRequest.Credentials = CredentialCache.DefaultCredentials;
const string HTTPHeaderCacheControlName = "cache-control";
const string HTTPHeaderValueCacheControlNo = "no-cache";
webRequest.Headers.Add(HTTPHeaderCacheControlName, HTTPHeaderValueCacheControlNo);
webRequest.Method = "POST";
ADODB.Stream fileStream = new ADODB.Stream();
fileStream.Type = ADODB.StreamTypeEnum.adTypeBinary;
fileStream.Mode = ADODB.ConnectModeEnum.adModeReadWrite;
fileStream.Open();
fileStream.LoadFromFile(info.Filename);
var byteData = fileStream.Read();
fileStream.Close();
ADODB.Stream mixedStream = new ADODB.Stream();
mixedStream.Mode = ADODB.ConnectModeEnum.adModeReadWrite;
mixedStream.Charset = "utf-8";
mixedStream.Open();
mixedStream.Type = ADODB.StreamTypeEnum.adTypeText;
mixedStream.WriteText(Environment.NewLine + "--" + HTTPBoundary + Environment.NewLine + "Content-Disposition: form-data; name=\"itemName\"" + Environment.NewLine + Environment.NewLine + Path.GetFileName(info.Filename));
mixedStream.WriteText(Environment.NewLine + "--" + HTTPBoundary + Environment.NewLine + "Content-Disposition: form-data; name=\"parentNickname\"" + Environment.NewLine + Environment.NewLine + info.ParentNickname);
mixedStream.WriteText(Environment.NewLine + "--" + HTTPBoundary + Environment.NewLine + "Content-Disposition: form-data; name=\"file\"; filename=\"" + info.Filename + "\"" + Environment.NewLine);
mixedStream.WriteText(Environment.NewLine);
mixedStream.Position = 0;
mixedStream.Type = ADODB.StreamTypeEnum.adTypeBinary;
mixedStream.Position = mixedStream.Size;
mixedStream.Write(byteData);
byteData = null;
mixedStream.Position = 0;
mixedStream.Type = ADODB.StreamTypeEnum.adTypeText;
mixedStream.Position = mixedStream.Size;
mixedStream.WriteText(Environment.NewLine + Environment.NewLine + "--" + HTTPBoundary + "--" + Environment.NewLine);
mixedStream.Position = 0;
mixedStream.Type = ADODB.StreamTypeEnum.adTypeBinary;
var read = mixedStream.Read();
webRequest.ContentLength = read.Length;
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(read, 0, read.Length);
requestStream.Close();
try
{
var response = (HttpWebResponse)webRequest.GetResponse();
}
catch (WebException exception)
{
using (var reader = new System.IO.StreamReader(exception.Response.GetResponseStream()))
{
string responseText = reader.ReadToEnd();
}
}
}
This seems to be not the perfect way to do this in C# but it works.
[Basically the same as this guy, unfortunately the thread died before being answered.]WebClient's UploadFile and UploadData not sending same headers (with multipart/form-data)
I can upload a file using the WebClients UploadFile, but I'm unable to upload the same exact file converted to a byte array using UploadData.
Fiddler difference:
On UploadData: Content-Length: 13264
Content-Type: multipart/form-data; boundary=---------------------8d77fde3018f8e5
On UploadFile: Content-Length: 13457
Content-Type: multipart/form-data; boundary=---------------------8d77fdcfcc453c5
Why is this happening? Currently the file i have is stored in memory and not on file, and saving the file locally isn't really an option.
Anyone has any ideas?
EDIT:
var bytes = System.IO.File.ReadAllBytes("dummy.pdf");
using (WebClient client = new WebClient())
{
client.Headers.Add("Access-Token", token);
client.Headers.Add("Client-Secret", clientSecret);
client.UploadFile("website", "dummy.pdf");
}
string boundary = "---------------------" + DateTime.Now.Ticks.ToString("x");
var newLine = Environment.NewLine;
var fileHeaderFormat = "--"+boundary + newLine +
"Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + newLine +
"Content-Type: application/octet-stream" + newLine + newLine;
var req = (HttpWebRequest)HttpWebRequest.Create(#"website");
req.Method = WebRequestMethods.Http.Post;
req.ContentType = "multipart/form-data; boundary=" + boundary;
req.Headers.Add("Access-Token", token);
req.Headers.Add("Client-Secret", clientSecret);
req.Headers.GetType().InvokeMember("ChangeInternal",
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod,
Type.DefaultBinder, req.Headers, new object[] { "Connection", "Keep-Alive" }
);
using (var reqStream = req.GetRequestStream())
{
var reqWriter = new StreamWriter(reqStream);
var tmp = string.Format(fileHeaderFormat, "file", "dummy.pdf");
reqWriter.Write(tmp);
reqWriter.Flush();
reqStream.Write(bytes, 0, bytes.Length);
}
var res = req.GetResponse();
using (var resStream = res.GetResponseStream())
{
var reader = new StreamReader(resStream);
var t = reader.ReadToEnd();
}
I have been trying for awhile now to log into a website using a WebRequest with no luck and I'm hoping that somebody can help me out. The login page uses "multipart/form-data; boundary" for its post data which I have never encountered before and I haven't been able to get it to work.
A successful post looks like this (courtesy of Tamper):
-----------------------------13327156328034
Content-Disposition: form-data; name="cc_session_id"
0vtgfe4bbhlh94f4vmmptctr06
-----------------------------13327156328034
Content-Disposition: form-data; name="cc_action"
cca_login
-----------------------------13327156328034
Content-Disposition: form-data; name="cc_failure_url"
https://www.fanduel.com/p/LoginPp
-----------------------------13327156328034
Content-Disposition: form-data; name="cc_success_url"
https://www.fanduel.com/
-----------------------------13327156328034
Content-Disposition: form-data; name="email"
*********
-----------------------------13327156328034
Content-Disposition: form-data; name="password"
*********
-----------------------------13327156328034
Content-Disposition: form-data; name="login"
Log in
-----------------------------13327156328034--
My connection method looks like this:
private static WebResponse Connect()
{
var manager = new SessionIDManager();
var boundary = "---------------------------" + DateTime.Now.Ticks;
var newLine = Environment.NewLine;
var propFormat = "--" + boundary + newLine +
"Content-Disposition: form-data; name=\"{0}\"" + newLine + newLine +
"{1}" + newLine;
var req = WebRequest.Create("https://www.fanduel.com/c/CCAuth");
var session = manager.CreateSessionID(HttpContext.Current);
req.Method = "POST";
req.ContentType = "multipart/form-data; boundary=" + boundary;
string formParams = string.Format(propFormat, "cc_session_id", session);
formParams += string.Format(propFormat, "cc_action", "cca_login");
formParams += string.Format(propFormat, "cc_failure_url", "https://www.fanduel.com/p/LoginPp");
formParams += string.Format(propFormat, "cc_success_url", "https://www.fanduel.com/");
formParams += string.Format(propFormat, "email", Credentials.ToInsecureString(Credentials.DecryptString(Settings.FanDuel.UserName)));
formParams += string.Format(propFormat, "password", Credentials.ToInsecureString(Credentials.DecryptString(Settings.FanDuel.Password)));
formParams += string.Format(propFormat, "login", "Log in");
formParams += "--" + boundary + "--";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
return req.GetResponse();
}
It produces the following post data:
-----------------------------635209175732301763
Content-Disposition: form-data; name="cc_session_id"
lptqmgshh2givmblbna4yeql
-----------------------------635209175732301763
Content-Disposition: form-data; name="cc_action"
cca_login
-----------------------------635209175732301763
Content-Disposition: form-data; name="cc_failure_url"
https://www.fanduel.com/p/LoginPp
-----------------------------635209175732301763
Content-Disposition: form-data; name="cc_success_url"
https://www.fanduel.com/
-----------------------------635209175732301763
Content-Disposition: form-data; name="email"
********
-----------------------------635209175732301763
Content-Disposition: form-data; name="password"
********
-----------------------------635209175732301763
Content-Disposition: form-data; name="login"
Log in
-----------------------------635209175732301763--
Unfortunately, the response's cookie isn't that of a successful login. At this point I don't know what else to do and I would appreciate any help anybody would be willing to offer me to get this working. Thanks.
Update: I Tried getting an initial response and then using that session id for my post, but still no luck. Does anybody have any ideas?
I've managed to get this working and optimized the method to the best of my ability.
private CookieContainer cookies = new CookieContainer();
private string loginCookie;
public bool IsLoggedIn { get; set; }
public void Login()
{
var boundary = "---------------------------" + DateTime.Now.Ticks;
var newLine = Environment.NewLine;
var propFormat = "--" + boundary + newLine +
"Content-Disposition: form-data; name=\"{0}\"" +
newLine + newLine + "{1}" + newLine;
var req = WebRequest.Create("https://www.fanduel.com/c/CCAuth") as HttpWebRequest;
req.CookieContainer = cookies;
req.Method = "POST";
req.ContentType = "multipart/form-data; boundary=" + boundary;
string formParams = string.Format(propFormat, "cc_session_id", new SessionIDManager().CreateSessionID(HttpContext.Current));
formParams += string.Format(propFormat, "cc_action", "cca_login");
formParams += string.Format(propFormat, "cc_failure_url", "https://www.fanduel.com/p/LoginPp");
formParams += string.Format(propFormat, "cc_success_url", "https://www.fanduel.com/");
formParams += string.Format(propFormat, "email", Credentials.ToInsecureString(Credentials.DecryptString(FanDuel.Default.UserName)));
formParams += string.Format(propFormat, "password", Credentials.ToInsecureString(Credentials.DecryptString(FanDuel.Default.Password)));
formParams += string.Format(propFormat, "login", "Log in");
formParams += "--" + boundary + "--";
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
var res = req.GetResponse();
res.Close();
loginCookie = req.Headers["Cookie"];
IsLoggedIn = res.ResponseUri == new Uri("https://www.fanduel.com/p/Home");
}
Then pass loginCookie to any other relevant WebRequest:
void SomeMethod()
{
var req = WebRequest.Create("SomeUri");
req.Headers.Add("Cookie", loginCookie);
var res = req.GetResponse();
}
I hope this helps somebody in the future.
I have a c# function that is used to upload a file to a PHP web service. The PHP web service is expecting the following
A POST parameter called UploadFileRequestDto containing some XML data
The File stream
For some odd reason the $_POST parameter contains the UploadFileRequestDto only some of the time. If I look at the contents of
file_get_contents("php://input"))
I can see that the request is comming through as expected with the UploadFileRequestDto included.
Doing a
print_r($_REQUEST)
is returning an empty array.
Can anyone help me with a solution to this problem, my C# function is stipulated below
public string UploadFile(UploadFileRequestDto uploadFileRequestDto,string fileToUpload, string fileUploadEndpoint)
{
try
{
var request = (HttpWebRequest)WebRequest.Create(fileUploadEndpoint);
request.ReadWriteTimeout = 1000 * 60 * 10;
request.Timeout = 1000 * 60 * 10;
request.KeepAlive = false;
var boundary = "B0unD-Ary";
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
var postData = "--" + boundary + "\r\nContent-Disposition: form-data;";
postData += "name=\"UploadFileRequestDto\"\r\n\r\n";
postData += string.Format("{0}\r\n", SerializeUploadfileRequestDto(uploadFileRequestDto));
postData += "--" + boundary + "\r\n";
postData += "--" + boundary + "\r\nContent-Disposition: form-data;name=\"file\";filename=\"" + Path.GetFileName(fileToUpload) + "\"\r\n";
postData += "Content-Type: multipart/form-data\r\n\r\n";
var byteArray = Encoding.UTF8.GetBytes(postData);
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] filedata = null;
using (var reader = new BinaryReader(File.OpenRead(fileToUpload)))
{
filedata = reader.ReadBytes((int)reader.BaseStream.Length);
}
request.ContentLength = byteArray.Length + filedata.Length + boundaryBytes.Length;
request.GetRequestStream().Write(byteArray, 0, byteArray.Length);
request.GetRequestStream().Write(filedata, 0, filedata.Length);
request.GetRequestStream().Write(boundaryBytes, 0, boundaryBytes.Length);
var response = request.GetResponse();
var data = response.GetResponseStream();
var sReader = new StreamReader(data);
var sResponse = sReader.ReadToEnd();
response.Close();
return sResponse.TrimStart(new char[] { '\r', '\n' });
}
catch (Exception ex)
{
LogProvider.Error(string.Format("OzLib.Infrastructure : WebHelper : public string UploadFile(UploadFileRequestDto uploadFileRequestDto, string fileUploadEndpoint) : Exception = {0}", ex.ToString()));
}
Ok I found the problem, the
post_max_size
setting in the php.ini was set to 8M and some of the files I was trying to upload exeeded 8M. Changed this setting to 16M and restarted the PHP service.
When the file size exeeds the limit that was set the $_POST global is empty.
I have a requirement to get cookies from login because i will apply this cookie in the same page. Here is my code
string boundary = "41184676334";
string username = "username";
string password = "password";
string login_post_data =
"POSTDATA=-----------------------------" + boundary +
"\nContent-Disposition: form-data; name=\"login\"" +
"\n\n" + username +
"\n-----------------------------" + boundary +
"\nContent-Disposition: form-data; name=\"key\"" +
"\n\n" + password +
"\n-----------------------------" + boundary +
"\nContent-Disposition: form-data; name=\"clcode\"" +
"\n\n" +
"\n-----------------------------" + boundary + "--";
var cookies = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://site.com/cgi-bin/login.pl?logout");
request.CookieContainer = cookies;
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=---------------------------" + boundary;
request.Host = "site.com";
request.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20100101 Firefox/14.0.1";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.Referer = "https://site.com/cgi-bin/login.pl?logout";
//request.Headers.Add("POSTDATA", post_data);
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(StrToByteArray(login_post_data), 0, StrToByteArray(login_post_data).Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
string temp = reader.ReadToEnd();
richTextBox1.Text = temp;
}
foreach (string c in response.Cookies)
{
listBox1.Items.Add(c);
}
The thing is "https://site.com/cgi-bin/login.pl?logout" is the same page after i logged in and i need to pass the cookie
It looks like you try to log in and log out at the same time with your request, sent to URL
https://site.com/cgi-bin/login.pl?logout
Remove the ?logout parameter and try again. Please update your question if it doesn't change anything.
Please explain further, what you're trying to achieve, so we can discuss if the code is correct.