Posted on 04-08-13 03:35 pm
Here's a little gem I've used in some of my applications:
Microsoft.Phone.Tasks.PhotoChooserTask t = new Microsoft.Phone.Tasks.PhotoChooserTask();
t.Completed += t_Completed;
t.Show();
...
void t_Completed(object sender, Microsoft.Phone.Tasks.PhotoResult e)
{
try
{
var req = HttpWebRequest.Create(new Uri("http://windowsphonehacker.com/upload.php", UriKind.Absolute));
req.Method = "POST";
req.ContentType = "application/octet-stream";
req.BeginGetRequestStream(callback =>
{
Stream poststream = req.EndGetRequestStream(callback);
var reqWriter = new StreamWriter(poststream);
byte[] buf = new byte[e.ChosenPhoto.Length];
e.ChosenPhoto.Read(buf, 0, (int)e.ChosenPhoto.Length);
string data = Convert.ToBase64String(buf);
reqWriter.Write(data);
reqWriter.Close();
req.BeginGetResponse(rep =>
{
WebResponse reply = req.EndGetResponse(rep);
Stream str = reply.GetResponseStream();
StreamReader reader = new StreamReader(str);
//success!
System.Diagnostics.Debug.WriteLine(reader.ReadToEnd());
this.Dispatcher.BeginInvoke(() =>
{
//do something to the UI thread
});
}, null);
}, null);
}
catch
{
this.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("An error occured!");
});
}
}
This will upload the image stream as base64 encoded POST data. To read it on the server, do something similar to the following:
$data = base64_decode(file_get_contents("php://input"));
Easy. Which is often typical (though sometimes very much untrue) of Windows Phone development and C#. Enjoy.