参考文章: 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,储存上传到服务器的图片,如图:
