做一个wp7手机上传图片到服务器的功能,具体丝路是在手机端做一个照相或者选择图片的功能,点击上传,在服务器端做一个一般处理程序,接受上传的文件,存入文件夹,下面是主要代码:
手机端代码:
/// <summary>
/// 点击上传照片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_Upload_Click(object sender, RoutedEventArgs e)
{
PhotoChooserTask task = new PhotoChooserTask();
task.PixelHeight = ;
task.PixelWidth = ;
task.ShowCamera = true;
task.Completed += new EventHandler<PhotoResult>(task_Completed);
task.Show(); }
//选择图片完成事件,上传图片操作
void task_Completed(object sender, PhotoResult e)
{
const int BLOCK_SIZE = ; //Code参数可以是存入服务器图片的命名
Uri uri = new Uri("http://localhost:58556/WebClientUpLoadHandler.ashx?Code=123456", UriKind.Absolute);
WebClient wc = new WebClient();
wc.AllowReadStreamBuffering = true;
wc.AllowWriteStreamBuffering = true; wc.OpenWriteCompleted += (s, args) =>
{
using (BinaryReader br = new BinaryReader(e.ChosenPhoto))
{
using (BinaryWriter bw = new BinaryWriter(args.Result))
{
long bCount = ;
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);
}
}
}; wc.WriteStreamClosed += (s, args) =>
{
MessageBox.Show("上传成功!");
}; wc.OpenWriteAsync(uri, "POST");
}
在服务器端建一个一般处理程序WebClientUpLoadHandler.ashx
代码为:
string name = context.Request.Params["Code"].ToString();
//获取从Silverlight客户端传来的信息
int length = context.Request.ContentLength;
byte[] bytes = context.Request.BinaryRead(length);
string uploadFolder = System.AppDomain.CurrentDomain.BaseDirectory + "\\upload"; //目录不存在则新建
if (!Directory.Exists(uploadFolder))
{
Directory.CreateDirectory(uploadFolder);
} ////写入文件
try
{
using (FileStream fs = new FileStream(uploadFolder + "\\" + name+".jpg", FileMode.Create, FileAccess.Write))
{
fs.Write(bytes, , bytes.Length);
}
context.Response.Write("服务器端成功");
}
catch { context.Response.Write("写入失败"); }
} public bool IsReusable
{
get
{
return false;
}
}
成功实现了从手机端上传图片功能,在此基础上可以继续添加别的功能,在不同应用中用到。