 |
|
 |
Hi,
The C# code works fine but the sr.ReadToEnd() return this:
Parse error: syntax error, unexpected T_STRING in C:\php\upload2.php on line 10
I'm very unexperienced with PHP. Anybody an idea how I can solve this?
Thanks!
Pete
|
|
|
|
 |
|
 |
Thanks for sharing
|
|
|
|
 |
|
 |
I'm using the UploadFileEx, post version, and get an exception in Tomcat. Stream ended unexpectedly. I see that the length is ok, I send all packets, but, seems server don't get it. I use the 8080 port.
Any idea?
|
|
|
|
 |
|
 |
I meet the same problem with Tomcat.
After reading the introduction of upload file standard,
it seems to require to do the following change to this line of code.
byte[] boundaryBytes =
Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] boundaryBytes =
Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
Hope that other guys with the same problem can this thread to solve the problem.
|
|
|
|
 |
|
 |
if you test application on Tomcat ,please modify it
because i got same problem and i fixed it by these.
.. Thank you for example ..
|
|
|
|
 |
|
 |
when i post my file to the webserver (https) i am getting an error that i cannot resolve.
Error: Cannot find bean: "Uploadbean" in any scope
any ideas on what would cause this error?
|
|
|
|
 |
|
 |
We had problems sending files larger then 7 Mb or so. The HttpWebRequest has a Timeout property, which defaults to 100000 ms, we upped that and it now seems to be working for larger files.
|
|
|
|
 |
|
 |
Worked great, after I added a mess of stream.Close() calls!
|
|
|
|
 |
|
 |
For some reason, the component would not work for me. I did find a more flexible solution, in the form of a cheap .NET component that allows you to navigate to pages, and interact with forms. It allows for multipart form post, and file upload, handling cookies and redirects and proxies automatically. It's pretty nifty.
You can find it over at http://foxtrot-xray.com/web-robot
|
|
|
|
 |
|
 |
solution u mentioned costs but i want to develop this solution my self. its a kind of study project.
|
|
|
|
 |
|
 |
it didnt work for me. i get a weird error from the webpage that i am sending the file to. something about UploadBean
|
|
|
|
 |
|
 |
i have been try to login on http://www.codeproject.com through C# code which i have attached with this mail. problem is this that code executes fine but results r not fine. every time it gives me start page as a response, not my page but start page. if someone be kind enough to rectify the problem and send the corrected code back to me. Code is here. as space is limited so iam posting it in 2 part. 1st part is below but the second one will be a reply to this message.
public void SendRequestTo()
{
string UserName;
string UserPwd;
string Request;
string Cookie="";
string RequestMethod="POST";
string uri="http://www.codeproject.com"
// Read UserName and User Password from the user in UserName and UserPwd respectively
Request="Email="+UserName+"&PassWord="+UserPwd;
NameValueCollection collHeader = new NameValueCollection();
HttpWebResponse webresponse;
try
{
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
webrequest.KeepAlive = true;
webrequest.Timeout=180000;
webrequest.Method = RequestMethod;
webrequest.Accept = "*/*";
webrequest.AllowAutoRedirect = false;
webrequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; " + "Windows NT 5.0;SV1;.NET CLR 1.1.4322)";
webrequest.ContentLength = Request.Length;
webrequest.ContentType = "text/html";
//"application/x-www-form-urlencoded";
int iCount = collHeader.Count;
string key;
string keyvalue;
for (int i=0; i < iCount; i++)
{
key = collHeader.Keys[i];
keyvalue = collHeader[i];
webrequest.Headers.Add(key, keyvalue);
}
CredentialCache wrCache = new CredentialCache();
wrCache.Add(new Uri(uri),"Basic",new NetworkCredential(UserName,UserPwd));
webrequest.Credentials = wrCache;
//Remove collection elements
collHeader.Clear();
webresponse =(HttpWebResponse)webrequest.GetResponse();
string uri2="";
|
|
|
|
 |
|
 |
WebHeaderCollection headers = webresponse.Headers;
if ((webresponse.StatusCode == HttpStatusCode.Found) ||
(webresponse.StatusCode == HttpStatusCode.Redirect) ||
(webresponse.StatusCode == HttpStatusCode.Moved) ||
(webresponse.StatusCode == HttpStatusCode.MovedPermanently))
{ // Get redirected uri
uri2 = headers["Location"] ;
uri2 = uri2.Trim();
}
//Check for any cookies
if (headers["Set-Cookie"] != null)
{Cookie = headers["Set-Cookie"];
}
string ReUri =uri2
//Check if there is any redirected URI.
webresponse.Close();
ReUri = ReUri.Trim();
if (ReUri.Length == 0) //No redirection URI
{ReUri = uri;
}
NameValueCollection collHeader = new NameValueCollection();
if (Cookie.Length > 0)
{collHeader.Add("Cookie",Cookie);
}
webrequest=null; webrequest = (HttpWebRequest)WebRequest.Create(ReUri);
webrequest.KeepAlive = true;
webrequest.Timeout=180000;
webrequest.Method = RequestMethod;
webrequest.Accept = "*/*";
webrequest.AllowAutoRedirect = false;
webrequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; " + "Windows NT 5.0;SV1;.NET CLR 1.1.4322)";
webrequest.ContentLength = Request.Length;
webrequest.ContentType = "text/html";
//"application/x-www-form-urlencoded";
int iCount2 = collHeader.Count;
string key2;
string keyvalue2;
for (int i2=0; i2 < iCount2; i2++)
{ key2 = collHeader.Keys[i2];
keyvalue2 = collHeader[i2];
webrequest.Headers.Add(key2, keyvalue2);
}
webrequest.Credentials = wrCache;
BuildReqStream(ref webrequest);
webresponse=null;
webresponse = (HttpWebResponse)webrequest.GetResponse();
Encoding enc = System.Text.Encoding.GetEncoding(1252);
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(),enc);
string Response = loResponseStream.ReadToEnd();
loResponseStream.Close();
webresponse.Close();
}//End of Try Block
catch (WebException e)
{System.Windows.Forms.Show(e.toString());
}
catch (System.Exception e)
{System.Windows.Forms.Show(e.toString());
}
finally
{BaseHttp=null;
}
System.IO.FileStream strr=new FileStream("C:\\itsnew.html",FileMode.Append);
byte[] bt=Encoding.GetEncoding(1252).GetBytes(Response);
strr.Write(bt,0,bt.Length);
} //End of SendRequestTo method
private void BuildReqStream(ref HttpWebRequest webrequest)
//This method build the request stream for WebRequest
{
byte[] bytes = Encoding.ASCII.GetBytes(Request);
System.Windows.Forms.MessageBox.Show(Request);
webrequest.ContentLength=bytes.Length;
Stream oStreamOut = webrequest.GetRequestStream();
oStreamOut.Write(bytes,0,bytes.Length);
oStreamOut.Close();
}//End BuildReqStream method
|
|
|
|
 |
|
 |
Thanks for the code...
But i am getting a problem right exactly while postinng.
I think its related to the request header...
Following code i have used in my application :-
private void cmdUpload_Click(object sender, System.EventArgs e)
{
string sURI = "http://adityamooley.net/photos/api/index.php";
CookieContainer cookies = new CookieContainer();
//add or use cookies
NameValueCollection querystring = new NameValueCollection();
querystring["aid"]="7";
querystring["username"]="aditya";
querystring["password"]="aditya";
querystring["function"]="cpgAPI.upload";
querystring["title"]="Title";
querystring["description"]="description";
querystring["keywords"]="keywords";
string uploadfile;// set to file to upload
uploadfile = @"e:\rahul\test.jpg";
//everything except upload file and url can be left blank if needed
string outdata = UploadFileEx(uploadfile,
sURI,"uploadfile", "image/pjpeg",
querystring,cookies);
}
the function code i didn't change.
at the statement :
WebResponse responce = webrequest.GetResponse();
i get the above mentioned error: (406) Not Acceptable.
If anyone have any idea how to solve it, it will be a great help.
--
Regards,
Rahul.
|
|
|
|
 |
|
 |
It is possible with the .NET 2.0 Framework, as it makes the WebClient a bit more flexible.
public class WebClientExtended : WebClient
{
private CookieContainer myContainer;
private HttpWebRequest myRequest;
private string myMethod;
public string Method
{
get { return myMethod; }
set { myMethod = value; }
}
public CookieContainer Cookies
{
get
{
if (myContainer == null)
{
myContainer = new CookieContainer();
}
return myContainer;
}
set
{
myContainer = value;
}
}
protected override WebRequest GetWebRequest(Uri address)
{
myRequest = (HttpWebRequest)base.GetWebRequest(address);
myRequest.Method = this.Method;
myRequest.CookieContainer = Cookies;
return myRequest;
}
protected override WebResponse GetWebResponse(WebRequest request)
{
return myRequest.GetResponse();
}
protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
{
return myRequest.EndGetResponse(result);
}
}
|
|
|
|
 |
|
 |
It's a nice idea, but you should not set CookieContainer unless you're sure that base.GetWebRequest is an HttpWebRequest.
protected override WebRequest GetWebRequest(Uri address) {
WebRequest wRequest = base.GetWebRequest(address);
if (wRequest is HttpWebRequest)
(wRequest as HttpWebRequest).CookieContainer = myContainer;
return wRequest;
}
|
|
|
|
 |
|
 |
I'd like to see an example where the cast would not yield an HttpWebRequest, not to say that you're wrong. Considering the way to get a fresh instance of an HttpWebRequest is through through the factory method which returns a WebRequest. HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.test.com"); So I'm not sure that the cast would ever yield a null result. You're also casting the object twice which would be unnecessary.
|
|
|
|
 |
|
 |
Thanks for posting this, it works great for storing cookies, just as advertised
I am having one issue, though. I have a single WebClientEx object that I share between methods, because I am using the Async methods and need to access the WebClientEx object after the operation has completed (via an event handler). Each function that initiates an action, like downloading or uploading some information, starts with:
wc = new WebClientEx();
Regardless of this, I am getting a WebException thrown that states, "The request was aborted: The request was canceled," the second time I use a function. The exception is thrown from:
protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
Oddly enough, as long as I don't use the same function twice, it does not error; for example: upload once, then download once works but upload once, then upload again fails.
I'm not sure if this is a result of your code or an error in my perception of WebClient, but if you have any suggestions, they would be much appreciated. Just to note, the problem that I am trying to solve is persisting the cookies obtained in WebClientEx between application instances, so I need to be able to access the cookie data from the Download*Completed and Upload*Completed event handlers.
Thank you.
|
|
|
|
 |
|
 |
Same problem here, but for me evertytime, when I want to use function after I've used another one error is raised.
|
|
|
|
 |
|
 |
I don't think so it could be possible, because
e.g.
i am trying to login on remote server through web client, in that case i have to maintain cookies in my cookie container, but still it couldn't possible using web client control to maintain cookie till logged in.
If anyone have solution for that problem so please help me.
Regards
Absolute Solution
sourabhsgandhi@gmail.com
|
|
|
|
 |
|
 |
Nice article- thanks!
This function only works with the GET method curently- here is a quick tip to add POST functionality to this guy:
public static string UploadFile(..., string method) // Added 'method'
{
...
Uri uri = null;
if(method == "GET")
{
string postdata = "?";
if(querystring != null)
{
foreach(string key in querystring.Keys)
{
postdata += key +"=" + querystring.Get(key)+"&";
}
}
uri = new Uri(url + postdata);
}
else
uri = new Uri(url);
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 = method;
// Build up the post message header
StringBuilder sb = new StringBuilder();
// Include any POST data (strings and such)
if(method == "POST")
{
if(querystring != null)
{
foreach(string key in querystring.Keys)
{
sb.Append("--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n" +
querystring.Get(key) + "\r\n");
}
}
}
// Finally include the file
sb.Append("--");
sb.Append(boundary);
...
Hope this helps someone trying to POST files and other data.
|
|
|
|
 |
|
 |
I managed to get it working for post forms.. modified code below..may be of use to others.
Public Function UploadFileEx2(ByVal theReferer As String, ByVal postMethod As String, ByVal uploadfilename As String, ByVal url As String, ByVal fileFormName As String, ByVal contenttype As String, ByVal querystring As System.Collections.Specialized.NameValueCollection, ByVal cookies As CookieContainer) As String
Try
Dim uri As Uri
If (fileFormName Is Nothing) OrElse (fileFormName.Length = 0) Then
fileFormName = "file"
End If
If (contenttype Is Nothing) OrElse (contenttype.Length = 0) Then
contenttype = "application/octet-stream"
End If
Dim postdata As String
postdata = "?"
If Not (querystring Is Nothing) Then
For Each key As String In querystring.Keys
postdata += key + "=" + querystring.Get(key) + "&"
Next
End If
If postMethod = "POST" Then
uri = New Uri(url)
Else
uri = New Uri(url + postdata)
End If
Dim boundary As String = "----------" + DateTime.Now.Ticks.ToString("x")
Dim webrequest As HttpWebRequest
webrequest = HttpWebRequest.Create(uri)
webrequest.CookieContainer = cookies
webrequest.ContentType = "multipart/form-data; boundary=" + boundary
webrequest.Method = postMethod
Dim sb As StringBuilder = New StringBuilder
If postMethod = "POST" Then
For Each key As String In querystring.Keys
sb.Append("--")
sb.Append(boundary)
sb.Append("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
sb.Append("Content-Disposition: form-data; name=""")
sb.Append(key)
sb.Append("""" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
sb.Append("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
sb.Append(querystring.Get(key))
sb.Append("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
Next
End If
sb.Append("--")
sb.Append(boundary)
sb.Append("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
sb.Append("Content-Disposition: form-data; name=""")
sb.Append(fileFormName)
sb.Append("""; filename=""")
sb.Append(Path.GetFileName(uploadfilename))
sb.Append("""")
sb.Append("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
sb.Append("Content-Type: ")
sb.Append(contenttype)
sb.Append("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
sb.Append("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
Dim postHeader As String = sb.ToString
Dim postHeaderBytes As Byte() = Encoding.UTF8.GetBytes(postHeader)
Dim boundaryBytes As Byte() = Encoding.ASCII.GetBytes("" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "--" + boundary + "" & Microsoft.VisualBasic.Chr(13) & "" & Microsoft.VisualBasic.Chr(10) & "")
Dim fileStream As FileStream = New FileStream(uploadfilename, FileMode.Open, FileAccess.Read)
Dim length As Long = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length
webrequest.ContentLength = length
webrequest.Referer = theReferer
Dim requestStream As Stream = webrequest.GetRequestStream
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length)
Dim sendBuffer(Math.Min(4096, fileStream.Length)) As Byte
Dim bytesRead As Integer = 0
'Dim r As New BinaryReader(fileStream)
Do
bytesRead = fileStream.Read(sendBuffer, 0, sendBuffer.Length)
If bytesRead = 0 Then Exit Do
requestStream.Write(sendBuffer, 0, bytesRead)
Loop
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
requestStream.Flush()
requestStream.Close()
Dim responce As WebResponse = webrequest.GetResponse
Dim s As Stream = responce.GetResponseStream
Dim sr As StreamReader = New StreamReader(s)
Dim buf As String = sr.ReadToEnd
Return sr.ReadToEnd
Catch ex As Exception
MsgBox("Error in uploadfileEx:" & ex.ToString)
Return ""
End Try
|
|
|
|
 |
|
 |
The line:
byte[] boundaryBytes =
Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
Should be:
byte[] boundaryBytes =
Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n")
It needs the two extra hyphens at the end otherwise you'll get an error 400 returned from the server.
I hope this helps someone as it nearly drove me insane !
|
|
|
|
 |
|
|
 |
|
 |
I get time-out exception when I try to upload file throught proxy
I've added webrequest.Proxy = new WebProxy(ProxyHost, ProxyPort) but it doesn't help
|
|
|
|
 |