Silverlight中文件的上传与下载

Silverlight应用开发过程中,有时候要用到文件的上传与下载功能,以下代码为提供了相关功能的解决方法。

 

一、上传功能:

UpLoadDoc.ashx文件代码(服务端):

 

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

namespace CITMPS.Web
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class UpLoadDoc : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            Stream fistream = context.Request.InputStream;
            try
            {
                string filename = DateTime.Now.Millisecond.ToString();
                byte[] buffer = new byte[4096];
                int byteread = 0;
                using (FileStream fi = File.Create(context.Server.MapPath("ClientBin/" + context.Request.QueryString["id"].ToString()), 4096))
                {
                    while ((byteread = fistream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        fi.Write(buffer, 0, byteread);
                    }
                }
                context.Response.ContentType = "text/plain";
                context.Response.Write("Succeeded!");
            }
            catch (Exception e)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("上传失败, 错误信息:" + e.Message);
            }
            finally
            {
                fistream.Dispose();
            }
        }

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

 

 

Silverlignt调用(客户端):

 

private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog()
            {
                //Filter = "Files (*.doc,*.pdf)|.doc;.pdf",
                Multiselect = false
            };
            if (dialog.ShowDialog() == true)
            {
                file = dialog.File;
                long length = file.Length / 1024;
                if (length <= fileMaxLength)
                {
                    Stream stream = file.OpenRead();
                    txtLoadedFile.Text = file.Name;
                    try
                    {
                        WebClient client = new WebClient();
                        HtmlElement element1 = HtmlPage.Document.GetElementById("Text11");
                        HtmlElement element2 = HtmlPage.Document.GetElementById("Text12");
                        Random random = new Random();
                        fileCode = DateTime.Now.ToString("yyyyMMddHHmmss") + random.Next(0, 9).ToString();
                        string name = fileCode + file.Extension;
                        string url = element1.GetAttribute("value").ToString() + "?id=" + name;
                        fileUri = element2.GetAttribute("value").ToString() + name;
                        client.OpenWriteCompleted += new OpenWriteCompletedEventHandler(client_OpenWriteCompleted);
                        client.OpenWriteAsync(new Uri(url, UriKind.Absolute), "POST", file.OpenRead());
                        btnUpload.IsEnabled = false;
                    }
                    catch
                    {
                        MessageBox.Show("上传文件失败。");
                    }
                }
                else
                {
                    MessageBox.Show("文件大小不能大于" + fileMaxLength.ToString() + "KB");
                }
            }
        }

        void client_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();
        }

 

 

二、下载功能:

 

DownloadFile.ashx文件代码(服务端):

 

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

namespace CITMPS.Web
{
    /// <summary>
    /// Summary description for DownloadFile
    /// </summary>
    public class DownloadFile : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            String fileName = context.Request.QueryString["fileName"]; //客户端保存的文件名
            fileName = HttpUtility.UrlDecode(fileName);
            String filePath = context.Server.MapPath("ClientBin/" + fileName); //路径
            FileInfo fileInfo = new FileInfo(filePath);
            if (fileInfo.Exists)
            {
                byte[] buffer = new byte[102400];
                context.Response.Clear();

                FileStream iStream = File.OpenRead(filePath);
                long dataLengthToRead = iStream.Length; //获取下载的文件总大小

                context.Response.ContentType = "application/octet-stream";
                context.Response.AddHeader("Content-Disposition", "attachment;  filename=" +
                                   HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                while (dataLengthToRead > 0 && context.Response.IsClientConnected)
                {
                    int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(102400));//'读取的大小

                    context.Response.OutputStream.Write(buffer, 0, lengthRead);
                    context.Response.Flush();
                    dataLengthToRead = dataLengthToRead - lengthRead;
                }
                context.Response.Close();
                context.Response.End();
            }
        }

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

 

Silverlignt调用(客户端):

 

private void btnDownload_Click(object sender, RoutedEventArgs e)

 {
            Button btn = sender as Button;
            SignDocument doc = btn.DataContext as SignDocument;
            Uri uri = new Uri(downloadFilePath + doc.Uri.Substring(doc.Uri.LastIndexOf('/') + 1), UriKind.Absolute);
            HtmlPage.Window.Navigate(uri, "_self");
 }

 

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的示例。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值