How to simply upload a generic file to php? - c#

I am using this code to upload a generic file stored in IsolatedStorage but it doesn't work:
string Filename = "aaa.dat";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://(mysite)/upload.php");
request.Method = "POST";
request.ContentType = "multipart/form-data";
string postData = String.Format("user_file", Filename);
// Getting the request stream.
request.BeginGetRequestStream
(result =>
{
// Sending the request.
using (var requestStream = request.EndGetRequestStream(result))
{
using (StreamWriter writer = new StreamWriter(requestStream))
{
writer.Write(postData);
writer.Flush();
}
}
// Getting the response.
request.BeginGetResponse(responseResult =>
{
var webResponse = request.EndGetResponse(responseResult);
using (var responseStream = webResponse.GetResponseStream())
{
using (var streamReader = new StreamReader(responseStream))
{
string srresult = streamReader.ReadToEnd();
}
}
}, null);
}, null);
This is my php file:
<?php
define("UPLOAD_DIR", "./uploads/");
if(isset($_POST['action']) and $_POST['action'] == 'upload')
{
if(isset($_FILES['user_file']))
{
$file = $_FILES['user_file'];
if($file['error'] == UPLOAD_ERR_OK and is_uploaded_file($file['tmp_name']))
{
move_uploaded_file($file['tmp_name'], UPLOAD_DIR.$file['name']);
echo "ok";
}
}
}
?>
Someone can tell me why this code doesn't work ?

It does not work because the following line
string postData = String.Format("user_file", Filename);
Is equivalent to
string postData = "user_file";
And the actual file data is never included into the request. String.Format is used to include variables into a pattern, ie:
string logMessage = String.Format("Uploading {0}", Filename);
Would generate "Uploading aaa.dat".
If you want to make this work you'll have to:
Read the contents of the file
Conform to the rules of multipart/form-data RFC1867

Related

Login into iCloud via Json Post request

I'm trying to log in into iCloud using a Json Post request in C#. Before trying to implement the code I was studying a little bit the iCloud requests using Chrome Console and using an Ad-on to replicate the requests in order to obtain the same result of the website.
First of All I checked the request directly from iCloud website:
And this is the response:
{
"serviceErrors" : [ {
"code" : "-20101",
"message" : "Il tuo ID Apple o la password non sono corretti."
} ]
}
Using "Advance REST Client" ad Chrome plugin to replicate the request I ve tried the same Json request to the same Url. But I get Empty response:
I Also tried to copy and paste the whole Header (All the settings) and than send the request but the response is the same:
Anyone has an Advice?
UPDATE: I tried to implement A Json request through c# program:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{accountName: \"briesanji #gmail.com\", password: \"testPassword\", rememberMe: false, trustTokens: []}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
The problem is that Execution breaks when the
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
is hit and it gives me this error: System.Net.WebException: 'Error Remote Server: (400) Request not valid.'
UPDATE: I solved in this way:
void POST(string url, string jsonContent)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);
request.ContentLength = byteArray.Length;
request.ContentType = #"application/json";
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
}
}
catch (WebException ex)
{
// Log exception and throw as for GET example above
}
}
string GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
Anyways I tested also the Answer and it was good to.. So I check it as valid thanks.
With this i dont get any error and the response content of the second request just tells me that there were too many failed logins for the test account...
private static void ICloud()
{
var cc = new CookieContainer();
var first = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin?widgetKey=83545bf919730e51dbfba24e7e8a78d2&locale=de_DE&font=sf");
first.Method = "GET";
first.CookieContainer = cc;
var response1 = (HttpWebResponse)first.GetResponse();
using (var streamReader = new StreamReader(response1.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
var second = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin");
second.ContentType = "application/json";
second.Method = "POST";
second.Accept = "application/json";
second.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
second.Referrer = "https://idmsa.apple.com/appleauth/auth/signin?widgetKey=83545bf919730e51dbfba24e7e8a78d2&locale=de_DE&font=sf";
second.Headers.Add("X-Requested-With", "XMLHttpRequest");
second.Headers.Add("X-Apple-Widget-Key", "83545bf919730e51dbfba24e7e8a78d2");
using (var streamWriter = new StreamWriter(second.GetRequestStream()))
{
string json = "{\"accountName\":\"test#icloud.com\",\"password\":\"test\",\"rememberMe\":false,\"trustTokens\":[]}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
try
{
var response2 = (HttpWebResponse)second.GetResponse();
using (var streamReader = new StreamReader(response2.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch(WebException we)
{
using (var r = new StreamReader(we.Response.GetResponseStream()))
{
var result2 = r.ReadToEnd();
}
}
}

Android app Json

I writing android app and faced problem.
I have API and write it to file.
Code of writing
string url2 = "http://new.murakami.ua/?mkapi=getProducts";
JsonValue json = await FetchAsync(url2);
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string filename = System.IO.Path.Combine(path, "myfile.txt");
using (var streamWriter = new StreamWriter(filename, true))
{
streamWriter.Write(json.ToString());
streamWriter.Close();
}
ParseAndDisplay1(json);
ParseAndDisplay2(json);
ParseAndDisplay3(json);
ParseAndDisplay4(json);
ParseAndDisplay5(json);
ParseAndDisplay6(json);
ParseAndDisplay7(json);
ParseAndDisplay8(json);
}
private async Task<JsonValue> FetchAsync(string url)
{
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.ContentType = "application/json";
request.Method = "GET";
// Send the request to the server and wait for the response:
using (WebResponse response = await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response:
using (Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON document object:
JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
//dynamic data = JObject.Parse(jsonDoc[15].ToString);
Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
// Return the JSON document:
return jsonDoc;
}
}
}
I want to read information from it and display.
I tried something like this, but it don't works.
private void ParseAndDisplay1(JsonValue json)
{
TextView productname = FindViewById<TextView> (Resource.Id.posttittle);
TextView price = FindViewById<TextView> (Resource.Id.price);
TextView weight = FindViewById<TextView> (Resource.Id.weight);
productname.Click += delegate {
var intent404 = new Intent (this, typeof(SoupesDetailActivity1));
StartActivity (intent404);
};
string path = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);
string filename = System.IO.Path.Combine (path, "myfile.txt");
using (var streamReader = new StreamReader (filename, true)) {
JsonValue firstitem = json [81];
productname.Text = firstitem ["post_title"];
price.Text = firstitem ["price"] + " грн";
weight.Text = firstitem ["weight"] + "г";
}
}
Can you help me with this problem?
There are many, many different ways to read/write data in .NET. This is just one fairly simple approach
// assuming data is System.Json.JsonValue with your data
// write data to file
File.WriteAllText(path, data.ToString());
// read back data
string rawdata = File.ReadAllText(path);
// parse it into a JsonValue
JsonValue json = JsonValue.Parse(rawdata);
Man you are using Xamarin. But here some tips of how I solve it in Android native code.
I saved the file in the Assets folder;
them saved the fale with .json extension not .txt;
I accessed it using this code:
private static String loadJSONFromAsset(Context context, String fileName) {
String json = null;
try {
InputStream is = context.getAssets().open("contactos/" + fileName + ".json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer);
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
After that I parse the JSON with no problem.
And it works perfectly, I hope it will help you.

i want to make the following curl call in my C# application

i want to make the following curl call in my C# application: i beginner of code
**this code get json response of cities on facebook contain character 'a' and character 'b' from facebook graph api i tried to make it i have error The request was aborted: The connection was closed unexpectedly **
private JArray Getcities(string token)
{
try
{
string s1 = "access_token="+Server.UrlEncode(token);
string s2 = "&batch=" + Server.UrlEncode(" [ { \"method\": \"get\", \"relative_url\":\"search?type=adgeolocation&location_types=city&region_id=3871&country_code=us&limit=3000&q=a\" }, { \"method\": \"get\", \"relative_url\": \"search?type=adgeolocation&location_types=city&region_id=3871&country_code=us&limit=3000&q=b\" } ]");
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/v2.3/");//make url
httpRequest.Method = "Post";
httpRequest.ContentType = "text/json; charset=utf-8";
byte[] bytedata = Encoding.UTF8.GetBytes(s1 + s2);
httpRequest.ContentLength = bytedata.Length;
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata,0,bytedata.Length);
requestStream.Close();
StreamReader reader;
HttpWebResponse httpWebResponse = (HttpWebResponse) httpRequest.GetResponse()
using (var responsestream = httpWebResponse.GetResponseStream())
{
reader = new StreamReader(responsestream, encoding: Encoding.UTF8);
}
var apiData = reader.ReadToEnd();
Response.Write(apiData);
var data = JArray.Parse(apiData).ToString();
//var s = data["data"].ToString();
var x = JArray.Parse(data);
return x;
}
The problem is with your using statement
using (var responsestream = httpWebResponse.GetResponseStream())
{
reader = new StreamReader(responsestream, encoding: Encoding.UTF8);
}
At the end of the using statement the stream gets disposed so it no longer works when you try read to end. It should work if you re-write like this.
byte[] apiData;
using (var responsestream = httpWebResponse.GetResponseStream())
{
reader = new StreamReader(responsestream, encoding: Encoding.UTF8);
apiData = reader.ReadToEnd();
}
Then the stream is disposed after reading all the data.

How to base64 encode a file and upload to PHP using windows phone?

I just want to upload a .dat file from a windows phone to a php script.
This is my code, but doesn't work. Can anyone see a reason why?
C#:
string fileBase64 = "UklGRt4lAABXQVZFZm10IBAAAAABAAEARKw...";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://...mysite.../upload.php");
request.Method = "POST";
request.ContentType = "application/octet-stream";
string postData = String.Format("file={0}", fileBase64);
// Getting the request stream.
request.BeginGetRequestStream
(result =>
{
// Sending the request.
using (var requestStream = request.EndGetRequestStream(result))
{
using (StreamWriter writer = new StreamWriter(requestStream))
{
writer.Write(postData);
writer.Flush();
}
}
// Getting the response.
request.BeginGetResponse(responseResult =>
{
var webResponse = request.EndGetResponse(responseResult);
using (var responseStream = webResponse.GetResponseStream())
{
using (var streamReader = new StreamReader(responseStream))
{
string srresult = streamReader.ReadToEnd();
}
}
}, null);
}, null);
PHP:
define("UPLOAD_DIR", "./uploads/");
if(isset($_POST['file']))
{
$base64_string = $_POST['file'];
$ifp = fopen( UPLOAD_DIR.'aaa.dat', "wb" );
fwrite( $ifp, base64_decode($base64_string) );
fclose( $ifp );
echo "ok";
echo $base64_string;
echo base64_decode($base64_string);
}else{
echo "no submit";
}
You’re abusing the HTTP protocol.
Here’s the correct way to upload files to the server. Be sure to read comments, and also you'll probably want to do this asynchronously. For the asynchronous path I'd suggest you try the new async-await feature of the C# language, it's very helpful for such tasks, compared to your Begin/End approach.

send xml file to handler using http-post

protected void UploadFile(object sender, EventArgs e)
{
if (fileUpload.HasFile)
{
if (fileUpload.PostedFile.ContentType == "text/xml")
{
Stream inputstream = fileUpload.PostedFile.InputStream;
byte[] streamAsBytes = (ConvertStreamToByteArray(inputstream));
string stringToSend = BitConverter.ToString(streamAsBytes);
xmlstream.Value = stringToSend;
sendXML.Visible = true;
infoLabel.Text = string.Empty;
/*
string path = Server.MapPath("GenericHandler.ashx");
WebClient wc = new WebClient();
wc.UploadFile(path,"POST", fileUpload.PostedFile);
Something like this maybe? But is there any way to do it without saving the file? */
}
else
{
infoLabel.Text = "Please select an XML file";
sendXML.Visible = false;
}
}
}
This is my current code. The xml gets saved in a hidden field as a hex string and sent via jquery ajax. But it would be much better to send the file itself and process it in the handler. Is that possible?
Try the following code, i haven't tested it but it should work, instead of string pass the byte[] to the method
private string PostData(string url, byte[] postData)
{
HttpWebRequest request = null;
Uri uri = new Uri(url);
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
using (Stream writeStream = request.GetRequestStream())
{
writeStream.Write(postData, 0, postData.Length);
}
string result = string.Empty;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
result = readStream.ReadToEnd();
}
}
}
return result;
}
Found the code here at Http Post in C#
Yes, you can create a HttpWebRequest, set it's Method to POST (if that's what you need) and then create a form field in the request with your file data. You will need to understand a little bit about how HTTP requests work and how to properly create that form field in the request, but it's doable (and not overly difficult).

Categories