07
2014
06

Silverlight通过WebClient上传图片到网站ClientBin文件夹

 

 

Silverlight对权限要求较为严格, 如果想上传文件到服务器中,要通过WebClient方式实现, 具体代码如下: 

 

Silverlight 端代码: 

MainPage.xaml.cs

      
        private void ImportImageButtonClick(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Image Files (*.png, *.jpg)|*.png;*.jpg";
            bool? dialogResult = openFileDialog.ShowDialog();         
            if (dialogResult.HasValue && dialogResult.Value == true)
            {
                Image image = new Image();
                var fileOpenRead = openFileDialog.File.OpenRead();
                {
                    string name = openFileDialog.File.Name;
                    string extension = name.Substring(name.LastIndexOf('.'), name.Length - name.LastIndexOf('.')); //取得扩展名(包括“.”)
                    uploadedName = DateTime.Now.ToString("yyyyMMddhhmmss") + extension; // 根据当前时间重命名
                    uploadImage(uploadedName, fileOpenRead);
                }
            }
        }

        static string webURL = "";
        static string WebURL
        {
            get
            {
                if (string.IsNullOrEmpty(webURL))
                {
                    System.Windows.Browser.HtmlDocument doc = System.Windows.Browser.HtmlPage.Document;
                    webURL = doc.DocumentUri.AbsoluteUri.Replace(doc.DocumentUri.AbsolutePath, "");
                }
                return webURL;
            }
        }

        static string uploadedName = "";
        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.WriteStreamClosed += new WriteStreamClosedEventHandler(webclient_WriteStreamClosed);
            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);
            }
        }

        void webclient_WriteStreamClosed(object sender, WriteStreamClosedEventArgs e)
        {
            //判断写入是否有异常
            //if (e.Error != null)
                //System.Windows.Browser.HtmlPage.Window.Alert(e.Error.Message.ToString());
           // else
               // "图片上传成功!!!";
        }

在调用Silverlight的网站项目下添加 DataHandler.ashx , 代码如下:

  [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class DataHandler : IHttpHandler
    {

        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;
            }
        }
    }


« 上一篇下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。