参考文章: http://www.cnblogs.com/wsdj-ITtech/archive/2009/08/26/1554056.html


1. ChainManager.xaml 前台

<Grid Grid.Row="0" Grid.Column="3" Grid.RowSpan="3" Margin="0,0,0,0" HorizontalAlignment="Left">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="50"/>
                            </Grid.ColumnDefinitions>

<Border BorderThickness="1" Width="110" Height="110" Margin="5" BorderBrush="#404040">
                                <Image x:Name="imgHead" Margin="5" Stretch="Fill"/>
                            </Border>
                            <telerik:RadButton Name="btnPhoto" Grid.Column="1" Content="选择" Width="40" Height="25" Click="btnPhoto_Click"  TabIndex="3"/>
                        </Grid>

2. XAMLChainManager.cs 后台

设定全局变量
        System.IO.FileInfo fileinfo = null;     //获取选定图片信息


/// <summary>
        /// 获取图片文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPhoto_Click(object sender, RoutedEventArgs e)
        {
            try
            {

      /*
               *   OpenWriteCompleted - 在打开用于上传的流完成时(包括取消操作及有错误发生时)所触发的事件
               *   WriteStreamClosed - 在写入数据流的异步操作完成时(包括取消操作及有错误发生时)所触发的事件
               *   UploadProgressChanged - 上传数据过程中所触发的事件。如果调用 OpenWriteAsync() 则不会触发此事件
               *   Headers - 与请求相关的的标头的 key/value 对**
               *   OpenWriteAsync(Uri address, string method, Object userToken) - 打开流以使用指定的方法向指定的 URI 写入数据
               *     Uri address - 接收上传数据的 URI
               *     string method - 所使用的 HTTP 方法(POST 或 GET)
               *     Object userToken - 需要上传的数据流
               */

             // 获取图片文件
                OpenFileDialog openFileDialog = new OpenFileDialog()
                {
                    Filter = "JPEG Images (*.jpg,*.jpeg)|*.jpg;*.jpeg|PNG Images (*.png)|*.png|All images|*.png;*.jpg;*.jpeg",
                    Multiselect = false
                };

if (openFileDialog.ShowDialog() == true)//.DialogResult.OK)
                {
                    fileinfo = openFileDialog.File;

if (fileinfo != null)
                    {

         // 图片显示在页面空间里
                        RadBitmap vwatermarkBitmap = new RadBitmap(fileinfo.OpenRead());
                        this.imgHead.Source = vwatermarkBitmap.Bitmap;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

/// <summary>
        /// 图片上传到服务器上
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                   if (fileinfo != null)
                    {
                        #region 把图片上传到服务器上

WebClient webclient = new WebClient();

          Uri WebUri = new Uri(Application.Current.Host.Source, "../");  //获取网站根目录
                         Uri upTargetUri = new Uri(String.Format(WebUri + "WebClientUpLoadStreamHandler.ashx?fileName={0}", fileinfo.Name.ToString()), UriKind.Absolute); //指定上传地址
                        webclient.OpenWriteCompleted += new OpenWriteCompletedEventHandler(Webclient_OpenWriteCompleted);
                        webclient.Headers["Content-Type"] = "multipart/form-data";
                        webclient.OpenWriteAsync(upTargetUri, "POST", fileinfo.OpenRead());
                        webclient.WriteStreamClosed += delegate(object sender1, WriteStreamClosedEventArgs f)
                        {
                            if (f.Error != null)
                            {
                                System.Windows.Browser.HtmlPage.Window.Alert(f.Error.Message.ToString());
                            }
                        };

#endregion
                    }
            }
            catch (Exception)
            {
                RadWindow.Alert("保存失败,请稍后重试!");
            }
        }

/// <summary>
        /// 将图片数据流发送到服务器上
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

void Webclient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
        {
            Stream clientStream = e.UserState as Stream;  // 需要上传的流(客户端流)
            Stream serverStream = e.Result;  // 目标地址的流(服务端流)
            byte[] buffer = new byte[4096];
            int readcount = 0;  

     // clientStream.Read - 将需要上传的流读取到指定的字节数组中
            while ((readcount = clientStream.Read(buffer, 0, buffer.Length)) > 0) 
            {

// serverStream.Write - 将指定的字节数组写入到目标地址的流
                serverStream.Write(buffer, 0, readcount);
            }

serverStream.Close();
            clientStream.Close();
        }


在数据存的是文件名称 (代码这里省略):

  chain.ImgName = fileinfo == null ? "" : fileinfo.Name.ToString(); //获取所选文件的名字;

从数据库中读到文件名称后,显示在页面上:

   imgHead.Source = new BitmapImage(new Uri("/Pics/" + chain.ImgName, UriKind.Relative));


3. 在服务端添加文件(WebClientUpLoadStreamHandler.ashx),如图

代码实现如下:

/// <summary>
    /// WebClientUpLoadStreamHandler 的摘要说明
    /// </summary>
    public class WebClientUpLoadStreamHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

public void ProcessRequest(HttpContext context)
        {
            //获取上传的数据流
            string fileNameStr = context.Request.QueryString["fileName"];

Stream sr = context.Request.InputStream;

try
            {
                string filename = "";
                filename = fileNameStr;

byte[] buffer = new byte[4096];

int bytesRead = 0;

//将当前数据流写入服务器端文件夹ClientBin下
                string targetPath = context.Server.MapPath("/ClientBin/Pics/" + filename);

using (FileStream fs = File.Create(targetPath, 4096))
                {
                    while ((bytesRead = sr.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        //向文件中写信息
                        fs.Write(buffer, 0, bytesRead);
                    }
                }

context.Response.ContentType = "text/plain";
                context.Response.Write("上传成功");
            }

catch (Exception e)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("上传失败, 错误信息:" + e.Message);
            }

finally
            {
                sr.Dispose();
            }
        }
    }

4.并且在服务端建立文件夹 Pics,储存上传到服务器的图片,如图:

silverlight中 设置 头像(添加图片)的更多相关文章

  1. Silverlight中文本框添加回车事件后,换行无法清除的解决方法

    在开发Silverlight的项目中,为了更好的用户体验,我们常要给一些控件添加一些快捷键.然而,在Silverlight中当用户回车提交后,光标停留在文本框的第二行怎么也清除不掉,经过一段时间研究, ...

  2. Gtk 窗口,控件,设置(添加图片等)

    1.关于窗口   // 创建顶层窗体,后面有POPUP的 GtkWidget *main_window; main_window = gtk_window_new (GTK_WINDOW_TOPLEV ...

  3. IOS 在IOS6中设置navigationBar背景图片 会有一条 黑色阴影 --- 解决方案

    //给navigationBar设置背景图片 if ([self.navigationController.navigationBar respondsToSelector:@selector(set ...

  4. GitHub 中 readme 如何添加图片

    一.Readme 是什么 readme文件一般是放在github 每个repo的根目录下,用来解释.说明本repo的主要内容和相关信息.而且在repo主页进去的时候会被自动加载.一般采用md标记的文本 ...

  5. 在tableView中设置cell的图片和文字

    // 设置UITableViewCellEditingStyle的 accessoryType UITableViewCellAccessoryNone,                   // d ...

  6. markdown中设置、调整图片尺寸

    使用百分比描述尺寸 <img src="https://img2018.cnblogs.com/blog/1122471/201902/1122471-2019022218575673 ...

  7. 一步一步学Silverlight 2系列(20):如何在Silverlight中与HTML DOM交互(下)

    述 Silverlight 2 Beta 1版本发布了,无论从Runtime还是Tools都给我们带来了很多的惊喜,如支持框架语言Visual Basic, Visual C#, IronRuby, ...

  8. 关于在Silverlight中添加图片的问题

    在Silverlight中添加图片,目前支持的Image格式有jpg和png两种,如何在目录中添加,有些什么技巧呢? <StackPanel Background="White&quo ...

  9. Silverlight 中图片路径的设置

    在Silverlight中图片的设置方法有几种 如上图在一个工程中有个images文件夹,buttons.xaml页面中的Image控件要引用一张图片 第一种方法 xaml: <Image x: ...

随机推荐

  1. 51nod-1627 瞬间移动(组合数+逆元)

    题目描述: 有一个无限大的矩形,初始时你在左上角(即第一行第一列),每次你都可以选择一个右下方格子,并瞬移过去(如从下图中的红色格子能直接瞬移到蓝色格子),求到第n行第m列的格子有几种方案,答案对10 ...

  2. C++标准模板库(STL)之String

    1.String的常用用法 在C语言中,使用字符数组char str[]来存字符串,字符数组操作比较麻烦,而且容易有'\0'的问题,C++在STL中加入string类型,对字符串常用的需求功能进行封装 ...

  3. kendo ui DatePicker 时区转换

    http://blog.darkthread.net/post-2013-06-25-json-date-timezone-issue.aspx

  4. 从零开始学Python 一

    一.安装 1.进入Python官网下载环境:https://www.python.org 2.根据自己的电脑选择安装版本,然后安装即可. 二.运行第一个程序 1.安装完Python,会自带一个编辑器, ...

  5. PlantUML + Chrome 联合使用

    之前都是本地下载安装一个PlantUML,安装过程有点复杂,涉及到的其他插件也有些多. 后面发现Chrome浏览器上提供了相关插件,整个过程简直太流畅了.记录下. 安装: 打开Chrome的线上应用商 ...

  6. day_45_Django

    day45 内容回顾 #### 1. HTTP协议 tcp/IP协议 HTTP特性: 无连接 请求--响应模式 请求格式 响应格式 Django相关 Django下载 命令行: pip install ...

  7. K8S配置安装全过程

    V1.11.1https://github.com/kubernetes/kubernetes/releases/tag/v1.11.1环境准备:系统:centos7.2.1511[root@mast ...

  8. Linux c使用gumbo库解析页面表单信息(二)

    一.如何在程序当中使用gumbo? 要想在代码中使用gumbo,仅仅包含gumbo头文件是不够的,必须在编译程序的时候加上-lgumbo选项,编译程序才会链接到gumbo库上面. 这是我编译gumbo ...

  9. 前端开发面试题总结之——JAVASCRIPT(二)

    ___________________________________________________________________________________ 相关知识点 数据类型.运算.对象 ...

  10. CodeForces - 1040B Shashlik Cooking(水题)

    题目: B. Shashlik Cooking time limit per test 1 second memory limit per test 512 megabytes input stand ...