Silverlight上傳圖片本文将演示如何使用Silverlight上传图片。 在Visual Studio 2008中新建一个Silverlight项目,创建时选中“Host the Silverlight application in a new Web site”复选框。 private void btnUpload_Click(object sender, RoutedEventArgs e)
{ OpenFileDialog dlg = new OpenFileDialog(); dlg.Multiselect = false; dlg.Filter = "JPG 图片 (*.jpg)|*.jpg|PNG 图片 (*.png)|*.png"; bool? result = dlg.ShowDialog(); if (result != null && result == true) { string name = dlg.File.Name; string extension = name.Substring(name.LastIndexOf('.'), name.Length - name.LastIndexOf('.')); //取得扩展名(包括“.”) string uploadedName = DateTime.Now.ToString("yyyyMMddhhmmss") + extension; // 根据当前时间重命名 uploadImage(uploadedName, dlg.File.OpenRead()); uploadedImageName.Text = string.Format("上传成功!已重命名为:{0}", uploadedName); } } uploadImage方法和其中用到的uploadData方法的代码如下: private void uploadImage(string fileName, Stream data)
{ Uri uri = new Uri(string.Format("/DataHandler.ashx?filename={0}", fileName), UriKind.Relative); WebClient client = new WebClient(); client.OpenWriteCompleted += delegate(object s, OpenWriteCompletedEventArgs e) { uploadData(data, e.Result); e.Result.Close(); data.Close(); }; client.OpenWriteAsync(uri); } private void uploadData(Stream input, Stream output)
{ byte[] buffer = new byte[4096]; int bytes; while ((bytes = input.Read(buffer, 0, buffer.Length)) != 0) { output.Write(buffer, 0, bytes); } } 在网站中添加一个Generic Handler 命名为DataHandler.ashx,后置代码如下: public void ProcessRequest(HttpContext context)
{ string filename = context.Request.QueryString["filename"].ToString(); public void ProcessRequest(HttpContext context) { string filename = context.Request.QueryString["filename"].ToString(); using (FileStream fs = File.Create(context.Server.MapPath("~/ClientBin/Images/" + filename))) { SaveImage(context.Request.InputStream, fs); } } private void SaveImage(Stream stream, FileStream fs) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0) { fs.Write(buffer, 0, bytesRead); } } public bool IsReusable { get { return false; } } 在ClientBin文件夹下面新建一个文件夹Images,到此全部工作完成,运行程序就可以上传图片了 代震军图片上传 http://www.cnblogs.com/daizhj/archive/2008/06/16/1222835.html silverlight 图片上传 http://www./html/download/code/2009/1123/258.html 异步上传技巧 http://www./html/tips/2010/0321/876.html silverlight+WCF 文件上传 支持断点续传 |
|
来自: 泉水930 > 《silverlight》