• Silverlight 实现文件上传


    通过web进行文件上传,一般要使用form表单,在silverlight里面没有内置form表单功能,参考牛人文章,实现Silverlight文件上传。只要Web.config文件中httpRuntime节点的maxRequestLength属性足够大,上传就不受限制。

    项目结构图:


    MainPage类源码:

    View Code
      1 namespace SilverlightDownAndUploadFile
      2 {
      3     public partial class MainPage : UserControl
      4     {
      5         private OpenFileDialog ofd;
      6         private AutoResetEvent autoEvent = new AutoResetEvent(false);
      7 
      8         public MainPage()
      9         {
     10             InitializeComponent();
     11         }
     12 
     13         private static HttpWebRequest CreateWebRequest(string requestUriString, string httpMethod)
     14         {
     15             try
     16             {
     17                 string ticks = Guid.NewGuid().ToString();
     18                 requestUriString = requestUriString + "/" + ticks;
     19                 HttpWebRequest request = (HttpWebRequest)WebRequestCreator.ClientHttp.Create(new Uri(requestUriString));
     20                 request.Method = httpMethod;
     21 
     22                 return request;
     23             }
     24             catch (Exception ex)
     25             {
     26                 return null;
     27             }
     28         }
     29         #region 上传
     30 
     31         private void ReadFileToRequestStream(BinaryReader fileStream, HttpWebRequest request)
     32         {
     33             try
     34             {
     35                 request.BeginGetRequestStream((requestAsyncResult) =>
     36                 {
     37                     Stream requestStream = null;
     38                     try
     39                     {
     40                         requestStream = request.EndGetRequestStream(requestAsyncResult);
     41                         if (null != requestStream)
     42                         {
     43                             SilverlightMultipartFormData form = new SilverlightMultipartFormData();
     44                             //form.AddFormField("devilField", "中国人");
     45                             int maxBufferLen = 25 * 1024;
     46                             byte[] buffer = new byte[maxBufferLen];
     47                             int bytesRead = fileStream.Read(buffer, 0, maxBufferLen);
     48                             int i = 0;
     49                             while (bytesRead != 0)
     50                             {
     51                                 i++;
     52                                 byte[] newBuffer = GetNewBuffer(buffer, bytesRead);
     53                                 form.AddStreamFile("package" + i, "package" + i, newBuffer);
     54                                 buffer = new byte[maxBufferLen];
     55                                 bytesRead = fileStream.Read(buffer, 0, maxBufferLen);
     56                             }
     57 
     58                             form.PrepareFormData();//结束
     59                             fileStream.Close();
     60                             request.ContentType = "multipart/form-data; boundary=" + form.Boundary;
     61                             foreach (byte byt in form.GetFormData())
     62                             {
     63                                 requestStream.WriteByte(byt);
     64                             }
     65                             requestStream.Close();
     66                             autoEvent.Set();//开始上传
     67                         }
     68                     }
     69                     catch (Exception ex)
     70                     { }
     71                     finally
     72                     {
     73                         if (null != requestStream)
     74                             requestStream.Close();
     75                         if (null != fileStream)
     76                             fileStream.Close();
     77                     }
     78                 }, null);
     79             }
     80             catch (Exception ex)
     81             {
     82 
     83             }
     84         }
     85 
     86         private void RequestAndUploadFile(BinaryReader br)
     87         {
     88             try
     89             {
     90                 if (null == br) return;
     91                 HttpWebRequest request = CreateWebRequest("http://localhost:13953/Upload.ashx", "POST");
     92                 ReadFileToRequestStream(br, request);
     93                 autoEvent.WaitOne();//等待流写入完毕
     94 
     95                 //上传
     96                 request.BeginGetResponse(
     97                             (asyncResult) =>
     98                             {
     99                                 if (request.HaveResponse)
    100                                 {
    101                                     try
    102                                     {
    103                                         WebResponse response = request.EndGetResponse(asyncResult);
    104 
    105                                         Stream responseStream = response.GetResponseStream();
    106                                         int bufferLen = 1024;
    107                                         byte[] buffer = new byte[bufferLen];
    108                                         int bytesRead = responseStream.Read(buffer, 0, bufferLen);
    109                                         responseStream.Close();
    110 
    111                                         string responseText = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
    112 
    113                                         ShowUploadResult(true);
    114                                     }
    115                                     catch (Exception ex)
    116                                     {
    117                                         ShowUploadResult(false);
    118                                     }
    119                                 }
    120                             }, null);
    121             }
    122             catch (Exception ex)
    123             {
    124                 ShowUploadResult(false);
    125             }
    126         }
    127 
    128         private void btnUpload_Click(object sender, RoutedEventArgs e)
    129         {
    130             ofd = new OpenFileDialog();
    131             ofd.Filter = "(*.rar)|*.rar";
    132             ofd.Multiselect = false;
    133 
    134             if (ofd.ShowDialog() == true)
    135             {
    136                 uploadProgress.Visibility = Visibility.Visible;
    137                 BinaryReader br = new BinaryReader(ofd.File.OpenRead());
    138                 RequestAndUploadFile(br);
    139             }
    140         }
    141 
    142         private void ShowUploadResult(bool isSucess)
    143         {
    144             this.Dispatcher.BeginInvoke(
    145                 () =>
    146                 {
    147                     uploadProgress.Visibility = Visibility.Collapsed;
    148                     if (isSucess)
    149                         MessageBox.Show("上传成功");
    150                     else
    151                         MessageBox.Show("上传失败.");
    152                 });
    153         }
    154         #endregion
    155 
    156         /// <summary>
    157         /// 获了实际接读取到的字节数组
    158         /// </summary>
    159         /// <param name="buffer"></param>
    160         /// <param name="bytesRead"></param>
    161         /// <returns></returns>
    162         private byte[] GetNewBuffer(byte[] buffer, int bytesRead)
    163         {
    164             byte[] newBuffer = new byte[bytesRead];
    165             for (int i = 0; i < bytesRead; i++)
    166             {
    167                 newBuffer[i] = buffer[i];
    168             }
    169             return newBuffer;
    170         }
    171     }
    172 }

    Upload.ashx文件源码:

    View Code
      1 namespace SilverlightDownAndUploadFile.Web
      2 {
      3     /// <summary>
      4     /// Upload 的摘要说明
      5     /// </summary>
      6     public class Upload : IHttpHandler
      7     {
      8 
      9         public void ProcessRequest(HttpContext context)
     10         {
     11             //context.Response.ContentType = "text/plain";
     12             //context.Response.Write("Hello World");
     13             Stream stream = null;
     14             try
     15             {
     16                 string path = context.Server.MapPath("~/Files/upload.rar");
     17                 int i = 0;
     18                 while (true)
     19                 {
     20                     i++;
     21                     string packageName = "package" + i;
     22                     HttpPostedFile uploadFile = context.Request.Files[packageName];
     23                     if (null != uploadFile)
     24                     {
     25                         stream = context.Request.Files[packageName].InputStream;
     26                         FileStream fs = null;
     27                         if (i == 1 && File.Exists(path))
     28                         {
     29                             fs = new FileStream(path, FileMode.Create, FileAccess.Write);
     30                         }
     31                         else
     32                         {
     33                             fs = new FileStream(path, FileMode.Append, FileAccess.Write);
     34                         }
     35 
     36                         using (BinaryWriter bw = new BinaryWriter(fs))
     37                         {
     38                             int maxBufferLen = 20 * 1024;//20K
     39                             byte[] buffer = new byte[maxBufferLen];
     40                             int bytesRead = stream.Read(buffer, 0, maxBufferLen);
     41                             while (bytesRead != 0)
     42                             {
     43                                 byte[] newBuff = GetNewBuffer(buffer, bytesRead);
     44                                 bw.Write(newBuff, 0, newBuff.Length);
     45 
     46                                 buffer = new byte[maxBufferLen];
     47                                 bytesRead = stream.Read(buffer, 0, maxBufferLen);
     48                             }
     49 
     50                             //返回本次上传字节数
     51                             context.Response.Write(stream.Length);
     52                             context.Response.Flush();
     53                         }
     54 
     55                         stream.Close();
     56                         fs.Close();
     57                     }
     58                     else
     59                     {
     60                         if (i != 1)
     61                             break;
     62                         else
     63                             i = 0;
     64                     }
     65                 }
     66 
     67                 context.Response.Write("Upload Success!");
     68                 context.Response.Flush();
     69                 context.Response.End();
     70             }
     71             catch (Exception ex)
     72             {
     73             }
     74             finally
     75             {
     76                 if (null != stream)
     77                     stream.Close();
     78             }
     79         }
     80 
     81         /// <summary>
     82         /// 获取实际读取到的字节数组
     83         /// </summary>
     84         /// <param name="buffer"></param>
     85         /// <param name="bytesRead"></param>
     86         /// <returns></returns>
     87         private byte[] GetNewBuffer(byte[] buffer, int bytesRead)
     88         {
     89             byte[] newBuffer = new byte[bytesRead];
     90             for (int i = 0; i < bytesRead; i++)
     91             {
     92                 newBuffer[i] = buffer[i];
     93             }
     94             return newBuffer;
     95         }
     96 
     97         public bool IsReusable
     98         {
     99             get
    100             {
    101                 return false;
    102             }
    103         }
    104     }
    105 }

    完整源码可从http://download.csdn.net/detail/lianchangshuai/4998494下载。

  • 相关阅读:
    归并排序
    [转]html5 Canvas画图教程(1)—画图的基本常识
    [转]浏览器工作原理
    [转]Web开发者和设计师必须要知道的 iOS 8 十个变化
    mobile web开发(1) html页面头部基本设置
    差点难产的HTML5
    感觉离开了好久
    Java----区别
    MySQL---sql语句优化
    MySQL---数据库优化
  • 原文地址:https://www.cnblogs.com/liancs/p/2863020.html
Copyright © 2020-2023  润新知