zoukankan      html  css  js  c++  java
  • 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("上传成功!", "文件已保存!");
        }
    }

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

  • 相关阅读:
    Git 分支[转]
    监听键盘的输入事件[转]
    github for windows的初步使用
    限制一个form被同时打开的数量 Limite The Number of Forms Opened at the same time
    android内存检测工具
    面试 9.26 总结
    canvas path paint 的使用(游戏必备)
    android知识点
    android查缺补漏
    AIDL的使用
  • 原文地址:https://www.cnblogs.com/xwgli/p/3254417.html
Copyright © 2011-2022 走看看