Silverlight学习笔记六(Silverlight 2.0/3.0/4.0图片上传)

上一篇做了个本地图片浏览的功能,这次找到图片上传的代码,记录一下。
添加一个“一般处理程序”Handler.ashx
大气象
<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

using System.IO;

public class Handler : IHttpHandler
{

    
public void ProcessRequest(HttpContext context)
    {
        
//获取上传的数据流
        Stream sr = context.Request.InputStream;
        
try
        {
            
//生成随机的文件名(本DEMO中的上传图片名称也可用参数方法传递过来)
            string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            Random rnd 
= new Random();
            
string filename = "";
            
for (int i = 1; i <= 32; i++)
            {
                filename 
+= chars.Substring(rnd.Next(chars.Length), 1);
            }

            
byte[] buffer = new byte[4096];
            
int bytesRead = 0;
            
//将当前数据流写入服务器端文件夹ClientBin下
            using (FileStream fs = File.Create(context.Server.MapPath("ClientBin/" + filename + ".jpg"), 4096))
            {
                
while ((bytesRead = sr.Read(buffer, 0, buffer.Length)) > 0)
                {
                    
//向文件中写信息
                    fs.Write(buffer, 0, bytesRead);
                }
            }

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

    
public bool IsReusable
    {
        
get
        {
            
return false;
        }
    }

}

 

新建一个silverlight用户控件UploadPic.xaml
大气象
<UserControl x:Class="SilverlightXML.UploadPic"
    xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width
="400" Height="300">
    
<Grid x:Name="LayoutRoot" Background="Black" ShowGridLines="False" Margin="8">
        
<Grid.ColumnDefinitions>
        
<ColumnDefinition Width="196" />
        
<ColumnDefinition Width="*" />
        
</Grid.ColumnDefinitions>
        
<Grid.RowDefinitions>
        
<RowDefinition Height="*" />
        
<RowDefinition Height="48" />
        
</Grid.RowDefinitions>
        
<ListBox x:Name="myList" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
            ItemsSource
="{Binding}"
            Grid.Row
="0"
            Grid.Column
="0"
            Grid.RowSpan
="2"
            SelectionChanged
="OnSelectionChanged" >
            
<ListBox.ItemTemplate>
            
<DataTemplate>
            
<TextBlock Text="{Binding Name}" />
            
</DataTemplate>
            
</ListBox.ItemTemplate>
        
</ListBox>
    
<!--<my:GridSplitter Width="1" HorizontalAlignment="Left" VerticalAlignment="Stretch" Grid.Column="1"></my:GridSplitter>-->

        
<Image x:Name="myImage" Grid.Column="1" />
        
<StackPanel Grid.Row="1" Background="white" Grid.ColumnSpan="2" Orientation="Horizontal" HorizontalAlignment="Stretch">
        
<Button Grid.Row="1"
        Grid.Column
="0"
        Content
="选择图片"
        Margin
="8" Click="OnClick" FontSize="16" Width="100"/>
        
<Button Grid.Row="1"
        Grid.Column
="2"
        Content
="上传该图片"
        Margin
="8" Click="OnUpLoadClick" FontSize="16" Width="100"/>
        
</StackPanel> 
    
</Grid>

</UserControl>

 

UploadPic.xaml.cs
大气象
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using System.Windows.Browser;
using System.IO;
using System.Windows.Media.Imaging;

namespace SilverlightXML
{
    
public partial class UploadPic : UserControl
    {
        
public UploadPic()
        {
            InitializeComponent();
        }
        
void OnClick(object sender, EventArgs args)
        {
            OpenFileDialog openFileDialog 
= new OpenFileDialog()
            {
                Filter 
= "Jpeg Files (*.jpg)|*.jpg|All Files(*.*)|*.*",
                Multiselect 
= true
            };

            
if (openFileDialog.ShowDialog() == true)//.DialogResult.OK)
            {
                myList.DataContext 
= openFileDialog.Files;
            }
        }

        
void OnUpLoadClick(object sender, EventArgs args)
        {
            
if (fi != null)
            {
                WebClient webclient 
= new WebClient();

                webclient.OpenWriteCompleted 
+= new OpenWriteCompletedEventHandler(webclient_OpenWriteCompleted);
                webclient.OpenWriteAsync(
new Uri("http://localhost:51262/SilverlightXMLSite/Handler.ashx", UriKind.Absolute), "POST", fi.OpenRead());
            }
            
else
            {
                HtmlPage.Window.Alert(
"请选取相应图片!!!");
            }
        }

        
void webclient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
        {
            
//将图片数据流发送到服务器上
            Stream inputStream = e.UserState as Stream;
            Stream outputStream 
= e.Result;

            
byte[] buffer = new byte[4096];
            
int bytesRead = 0;

            
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                outputStream.Write(buffer, 
0, bytesRead);
            }
            outputStream.Close();
            inputStream.Close(); 
            HtmlPage.Window.Alert(
"图片上传成功!!!");
        }


        FileInfo fi; 
//获取选定图片信息//silverlight 2.0中是FileDialogFileInfo

        
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            
if ((e.AddedItems != null&& (e.AddedItems.Count > 0))
            {
                fi 
= e.AddedItems[0as FileInfo;

                
if (fi != null)
                {
                    
using (Stream stream = fi.OpenRead())
                    {
                        BitmapImage image 
= new BitmapImage();
                        image.SetSource(stream);
                        myImage.Source 
= image;
                        myImage.Visibility 
= Visibility.Visible;
                        stream.Close();
                    }
                }
            }
        }

    }

}

估计不能上传大文件,有专门的开源项目,有空找找。

posted @ 2010-06-13 09:43  大气象  阅读(1353)  评论(3编辑  收藏  举报
http://www.tianqiweiqi.com