Wp7: 调用摄像头拍照并上传图片(完整版)

本例通过webclient上传图片,首先在Mian.xaml.cs中:

private void SelectButton_Click(object sender, RoutedEventArgs e)
{
PhotoChooserTask task = new PhotoChooserTask();
task.Completed += task_Completed;
task.Show();
}

private void task_Completed(object sender, PhotoResult e)
{
if (e.TaskResult != TaskResult.OK)
return;

const int BLOCK_SIZE = 4096;

Uri uri = new Uri("http://localhost:13235/WebClientUpLoadHandler.ashx", UriKind.Absolute);

WebClient wc = new WebClient();
wc.AllowReadStreamBuffering = true;
wc.AllowWriteStreamBuffering = true;

// what to do when write stream is open
wc.OpenWriteCompleted += (s, args) =>
{
using (BinaryReader br = new BinaryReader(e.ChosenPhoto))
{
using (BinaryWriter bw = new BinaryWriter(args.Result))
{
long bCount = 0;
long fileSize = e.ChosenPhoto.Length;
byte[] bytes = new byte[BLOCK_SIZE];
do
{
bytes = br.ReadBytes(BLOCK_SIZE);
bCount += bytes.Length;
bw.Write(bytes);
} while (bCount < fileSize);
}
}
};

// what to do when writing is complete
wc.WriteStreamClosed += (s, args) =>
{
MessageBox.Show("Send Complete");
};

// Write to the WebClient
wc.OpenWriteAsync(uri, "POST");
}

在asp.net  server端新建一个ashx handler:

    /// <summary>
///新建一个ashx类处理上传数据
/// </summary>
public class WebClientUpLoadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//获取从Silverlight客户端传来的信息
int length = context.Request.ContentLength;
byte[] bytes = context.Request.BinaryRead(length);
string uploadFolder = System.AppDomain.CurrentDomain.BaseDirectory + "\\uploadvoice";
//目录不存在则新建
//if (!System.IO.Directory.Exists(uploadFolder))
//{
// System.IO.Directory.CreateDirectory(uploadFolder);
//}
System.IO.FileMode fileMode = System.IO.FileMode.Create;

////写入文件
try
{
using (System.IO.FileStream fs = new System.IO.FileStream(uploadFolder + "\\" + "name", fileMode, System.IO.FileAccess.Write))
{
fs.Write(bytes, 0, bytes.Length);
} context.Response.Write("服务器端成功");
}
catch { context.Response.Write("写入失败"); }


}

public bool IsReusable
{
get
{
return false;
}
}

}



posted @ 2012-03-19 14:24  newShit  阅读(1452)  评论(10编辑  收藏  举报