wp7图片上传服务器
做一个wp7手机上传图片到服务器的功能,具体丝路是在手机端做一个照相或者选择图片的功能,点击上传,在服务器端做一个一般处理程序,接受上传的文件,存入文件夹,下面是主要代码:
手机端代码:
1 /// <summary> 2 /// 点击上传照片 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 private void btn_Upload_Click(object sender, RoutedEventArgs e) 7 { 8 PhotoChooserTask task = new PhotoChooserTask(); 9 task.PixelHeight = 100; 10 task.PixelWidth = 100; 11 task.ShowCamera = true; 12 task.Completed += new EventHandler<PhotoResult>(task_Completed); 13 task.Show(); 14 15 } 16 //选择图片完成事件,上传图片操作 17 void task_Completed(object sender, PhotoResult e) 18 { 19 const int BLOCK_SIZE = 4096; 20 21 //Code参数可以是存入服务器图片的命名 22 Uri uri = new Uri("http://localhost:58556/WebClientUpLoadHandler.ashx?Code=123456", UriKind.Absolute); 23 WebClient wc = new WebClient(); 24 wc.AllowReadStreamBuffering = true; 25 wc.AllowWriteStreamBuffering = true; 26 27 wc.OpenWriteCompleted += (s, args) => 28 { 29 using (BinaryReader br = new BinaryReader(e.ChosenPhoto)) 30 { 31 using (BinaryWriter bw = new BinaryWriter(args.Result)) 32 { 33 long bCount = 0; 34 long fileSize = e.ChosenPhoto.Length; 35 byte[] bytes = new byte[BLOCK_SIZE]; 36 do 37 { 38 bytes = br.ReadBytes(BLOCK_SIZE); 39 bCount += bytes.Length; 40 bw.Write(bytes); 41 } while (bCount < fileSize); 42 } 43 } 44 }; 45 46 wc.WriteStreamClosed += (s, args) => 47 { 48 MessageBox.Show("上传成功!"); 49 }; 50 51 wc.OpenWriteAsync(uri, "POST"); 52 }
在服务器端建一个一般处理程序WebClientUpLoadHandler.ashx
代码为:
1 string name = context.Request.Params["Code"].ToString(); 2 //获取从Silverlight客户端传来的信息 3 int length = context.Request.ContentLength; 4 byte[] bytes = context.Request.BinaryRead(length); 5 string uploadFolder = System.AppDomain.CurrentDomain.BaseDirectory + "\\upload"; 6 7 //目录不存在则新建 8 if (!Directory.Exists(uploadFolder)) 9 { 10 Directory.CreateDirectory(uploadFolder); 11 } 12 13 ////写入文件 14 try 15 { 16 using (FileStream fs = new FileStream(uploadFolder + "\\" + name+".jpg", FileMode.Create, FileAccess.Write)) 17 { 18 fs.Write(bytes, 0, bytes.Length); 19 } 20 context.Response.Write("服务器端成功"); 21 } 22 catch { context.Response.Write("写入失败"); } 23 } 24 25 public bool IsReusable 26 { 27 get 28 { 29 return false; 30 } 31 }
成功实现了从手机端上传图片功能,在此基础上可以继续添加别的功能,在不同应用中用到。