Silverlight从客户端上传文件到服务器

这里介绍的是一种利用WebClient手动发送Stream到服务器页面的上传文件方法。

一、服务器接收文件

这里使用一个ASHX页面来接收和保存Silverlight传来的Stream,页面代码如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace Silverlight
{
    /// <summary>
    /// FileUploadHandler 的摘要说明
    /// </summary>
    public class FileUploadHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //获取上传参数 - 文件名
              string fileName = context.Request["FileName"];

            //获取上传的数据流
              using (Stream inputStream = context.Request.InputStream)
            {
                try
                {
                    //数据缓冲区
                       byte[] buffer = new byte[4096];
                    int bytesRead = 0;

                    //准备保存路径和文件名
                       string filePath = string.Format(@"D:\FileUpload\");

                    //检查保存路径是否存在
                       if (!Directory.Exists(filePath))
                    {
                        //不存在进行创建
                        Directory.CreateDirectory(filePath);
                    }

                    //准备写入文件流
                       using (FileStream fs = File.Create(filePath + fileName, 4096))
                    {
                        //开始循环写入文件
                           while ((bytesRead = inputStream.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);
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

这里保存文件的主要流程就是接收上传参数,准备保存文件,通过读取上传流保存文件内容。

二、客户端发送文件

客户端发送文件使用的是WebClient类。

首先建立一个WebClient连接:

//准备上传连接
WebClient uploadClient = new WebClient();
uploadClient.Headers["Content-Type"] = "multipart/form-data";

//连接打开后的操作
uploadClient.OpenWriteCompleted += uploadClient_OpenWriteCompleted;
//流写入完成后的操作
uploadClient.WriteStreamClosed += uploadClient_WriteStreamClosed;

//打开上传连接
uploadClient.OpenWriteAsync(new Uri("", UriKind.Relative), "POST", fileStream);

WebClient打开连接后的处理:

void uploadClient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
    //将文件数据流发送到服务器上

    // e.UserState - 需要上传的流(客户端流)
    using (Stream clientStream = e.UserState as Stream)
    {
        // e.Result - 目标地址的流(服务端流)
        using (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);
            }
        }
    }
}

WebClient连接关闭后的处理:

void uploadClient_WriteStreamClosed(object sender, WriteStreamClosedEventArgs e)
{
    //判断写入是否有异常
    if (e.Error != null)
    {
        MessageBox.Show("上传失败!", e.Error.Message.ToString());
    }
    else
    {
        MessageBox.Show("上传成功!", "文件已保存!");
    }
}

客户端这边主要就是打开连接,然后打开服务器的接收流,然后传输文件数据流到服务器。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Silverlight文件 v4.2源码 程序介绍: 提供了几种上模式,单文件,多文件,集成js文件的方式上文件。 将Silverlight工具集成到网页文件中需要进行简单的配置,看 如下各项参数作用。 配置: MaxFileSizeKB: 文件大小 KBs. MaxUploads: 同时上文件的最大数量 FileFilter: 文件类型过滤, 假如只使用jpeg文件: FileFilter=Jpeg (*.jpg) |*.jpg CustomParam: 自定义参数, 在WCF webservice可用 DefaultColor: 控件的默认颜色, 例如: LightBlue ChunkSize: 上块中的每个字节的大小bytes (最小 4096, 默认是 4194304) (仅用于 HttpUploader) UploadHandlerName: 指定HttpUploadHandler名称, 例如: "PHPUpload.php" 用于处理php上. Parameters: <asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/mpost.SilverlightMultiFileUpload.xap" MinimumVersion="2.0.30523" Width="415" Height="280" InitParameters ="MaxFileSizeKB=1000,MaxUploads=2,FileFilter=,CustomParam=1,DefaultColor=LightBlue" /> 事件: AllFilesFinished - 当所有文件完成上时触发 (当上过程中发生错误无效) SingleFileUploadFinished - 单文件完成时触发 ErrorOccurred - 当上过程中有错误时触发 属性: TotalUploadedFiles: 所有上文件数量 TotalFilesSelected: 列表中文件总数 Percentage: 总上进度百分比 动作: 可以被JavaScript触发: StartUpload: 开始上 ClearList: 清理列表 SelectFiles: 由于安全限制Silverlight 3中不可用。查看testpages中的示例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值