程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> Silverlight文件上傳下載完成辦法(下載保留)

Silverlight文件上傳下載完成辦法(下載保留)

編輯:C#入門知識

Silverlight文件上傳下載完成辦法(下載保留)。本站提示廣大學習愛好者:(Silverlight文件上傳下載完成辦法(下載保留))文章只能為提供參考,不一定能成為您想要的結果。以下是Silverlight文件上傳下載完成辦法(下載保留)正文


search了異常多的文章,總算委曲完成了。有很多不完美的處所。


在HCLoad.Web項面前目今新建目次Pics復制一張圖片到根目次下。

圖片名:Bubble.jpg 右擊->屬性->生成操作:Resource


UC_UpDown.xaml

<UserControl x:Class="HCLoad.UC_UpDown"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  Width="500" Height="500">
  <StackPanel Background="White" Height="450">
    <Button Content="down" Click="Button_Click"></Button>
    <HyperlinkButton Content="下載保留" NavigateUri="http://localhost:4528/download.ashx?fileName=aa.txt" TargetName="_self" x:Name="lBtnDown" />
    <TextBlock x:Name="tbMsgString" Text="下載進度" TextAlignment="Center" Foreground="Green"></TextBlock>
    <Button x:Name="btnDownload" Content="DownLoad Pictures" Width="150" Height="35" Margin="15" Click="btnDownload_Click"/>
    <Border Background="Wheat" BorderThickness="5" Width="400" Height="280">
      <Image x:Name="imgDownLoad" Width="400" Height="300" Margin="15" Stretch="Fill"/>
    </Border>
    <Button x:Name="btnUpLoad" Content="UpLoad Pictures" Width="150" Height="35" Margin="15" Click="btnUpLoad_Click"/>
  </StackPanel>
</UserControl>

UC_UpDown.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.Media.Imaging; //由於要應用BitmapImage
using System.IO; //由於要應用Stream

namespace HCLoad
{
  public partial class UC_UpDown : UserControl
  {
    //1、WebClient 對象一次只能啟動一個要求。假如在一個要求完成(包含失足和撤消)前,即IsBusy為true時,停止第二個要求,則第二個要求將會拋出 NotSupportedException 類型的異常
    //2、假如 WebClient 對象的 BaseAddress 屬性不為空,則 BaseAddress 與 URI(絕對地址) 組合在一路組成相對 URI
    //3、WebClient 類的 AllowReadStreamBuffering 屬性:能否對從 Internet 資本吸收的數據做緩沖處置。默許值為true,將數據緩存在客戶端內存中,以便隨時被運用法式讀取



    //獲得選定圖片信息
    System.IO.FileInfo fileinfo;
    public UC_UpDown()
    {
      InitializeComponent();
    }
    #region 下載圖片
    private void btnDownload_Click(object sender, RoutedEventArgs e)
    {
      //向指定的Url發送下載流數據要求 
      String imgUrl = "http://localhost:4528/Bubble.jpg";
      Uri endpoint = new Uri(imgUrl);

      WebClient client = new WebClient();
      client.OpenReadCompleted += new OpenReadCompletedEventHandler(OnOpenReadCompleted);
      client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(clientDownloadStream_DownloadProgressChanged);
      client.OpenReadAsync(endpoint);
    }
    void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {

      //OpenReadCompletedEventArgs.Error - 該異步操作時代能否產生了毛病
      //OpenReadCompletedEventArgs.Cancelled - 該異步操作能否已被撤消
      //OpenReadCompletedEventArgs.Result - 下載後的 Stream 類型的數據
      //OpenReadCompletedEventArgs.UserState - 用戶標識

      if (e.Error != null)
      {
        MessageBox.Show(e.Error.ToString());
        return;
      }
      if (e.Cancelled != true)
      {
        //獲得下載的流數據(在此處是圖片數據)並顯示在圖片控件中
        //Stream stream = e.Result;
        //BitmapImage bitmap = new BitmapImage();
        //bitmap.SetSource(stream);
        //imgDownLoad.Source = bitmap;
        Stream clientStream = e.UserState as Stream;
        Stream serverStream = (Stream)e.Result;
        byte[] buffer = new byte[serverStream.Length];
        serverStream.Read(buffer, 0, buffer.Length);
        clientStream.Write(buffer, 0, buffer.Length);
        clientStream.Close();
        serverStream.Close();

      }



    }

    void clientDownloadStream_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
      //DownloadProgressChangedEventArgs.ProgressPercentage - 下載完成的百分比
      //DownloadProgressChangedEventArgs.BytesReceived - 以後收到的字節數
      //DownloadProgressChangedEventArgs.TotalBytesToReceive - 總共須要下載的字節數
      //DownloadProgressChangedEventArgs.UserState - 用戶標識

      this.tbMsgString.Text = string.Format("完成百分比:{0} 以後收到的字節數:{1} 材料年夜小:{2} ",
       e.ProgressPercentage.ToString() + "%",
       e.BytesReceived.ToString(),
       e.TotalBytesToReceive.ToString());

    }

    #endregion

    #region 上傳圖片
    private void btnUpLoad_Click(object sender, RoutedEventArgs e)
    {
      /**/
      /*
     *   OpenWriteCompleted - 在翻開用於上傳的流完成時(包含撤消操作及有毛病產生時)所觸發的事宜
     *   WriteStreamClosed - 在寫入數據流的異步操作完成時(包含撤消操作及有毛病產生時)所觸發的事宜
     *   UploadProgressChanged - 上傳數據進程中所觸發的事宜。假如挪用 OpenWriteAsync() 則不會觸發此事宜
     *   Headers - 與要求相干的的標頭的 key/value 對**
     *   OpenWriteAsync(Uri address, string method, Object userToken) - 翻開流以應用指定的辦法向指定的 URI 寫入數據
     *     Uri address - 吸收上傳數據的 URI
     *     string method - 所應用的 HTTP 辦法(POST 或 GET)
     *     Object userToken - 須要上傳的數據流
     */


      OpenFileDialog openFileDialog = new OpenFileDialog()
      { //彈出翻開文件對話框請求用戶本身選擇在當地端翻開的圖片文件
        Filter = "Jpeg Files (*.jpg)|*.jpg|All Files(*.*)|*.*",
        Multiselect = false //不許可多選 
      };

      if (openFileDialog.ShowDialog() == true)//.DialogResult.OK)
      {
        //fileinfo = openFileDialog.Files; //獲得所選擇的文件,個中Name為文件名字段,作為綁定字段顯示在前端
        fileinfo = openFileDialog.File;

        if (fileinfo != null)
        {
          WebClient webclient = new WebClient();

          string uploadFileName = fileinfo.Name.ToString(); //獲得所選文件的名字

          #region 把圖片上傳到辦事器上

          Uri upTargetUri = new Uri(String.Format("http://localhost:4528/WebClientUpLoadStreamHandler.ashx?fileName={0}", uploadFileName), UriKind.Absolute); //指定上傳地址

          webclient.OpenWriteCompleted += new OpenWriteCompletedEventHandler(webclient_OpenWriteCompleted);
          webclient.Headers["Content-Type"] = "multipart/form-data";

          webclient.OpenWriteAsync(upTargetUri, "POST", fileinfo.OpenRead());
          webclient.WriteStreamClosed += new WriteStreamClosedEventHandler(webclient_WriteStreamClosed);

          #endregion

        }
        else
        {
          MessageBox.Show("請拔取想要上載的圖片!!!");
        }
      }

    }



    void webclient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
    {

      //將圖片數據流發送到辦事器上

      // e.UserState - 須要上傳的流(客戶端流)
      Stream clientStream = e.UserState as Stream;
      // e.Result - 目的地址的流(辦事端流)
      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);
      }
      serverStream.Close();
      clientStream.Close();


    }

    void webclient_WriteStreamClosed(object sender, WriteStreamClosedEventArgs e)
    {
      //斷定寫入能否有異常
      if (e.Error != null)
      {
        System.Windows.Browser.HtmlPage.Window.Alert(e.Error.Message.ToString());
      }
      else
      {
        System.Windows.Browser.HtmlPage.Window.Alert("圖片上傳勝利!!!");
      }
    }
    #endregion

    private void Button_Click(object sender, RoutedEventArgs e)
    {
      //這類辦法弄不定,似乎提醒跨域操作。
      //提醒:毛病:Unhandled Error in Silverlight Application 跨線程拜訪有效。
      //Uri upTargetUri = new Uri(String.Format("http://localhost:4528/download.ashx?filename={0}", "123.jpg"), UriKind.Absolute); //指定上傳地址
      //WebRequest request = WebRequest.Create(upTargetUri);
      //request.Method = "GET";
      //request.ContentType = "application/octet-stream";
      //request.BeginGetResponse(new AsyncCallback(RequestReady), request);

      //經由過程挪用js代碼下載,比擬簡略。
      System.Windows.Browser.HtmlPage.Window.Eval("window.location.href='http://localhost:4528/download.ashx?filename=123.jpg';");
    }
    void RequestReady(IAsyncResult asyncResult)
    {
      MessageBox.Show("RequestComplete");
    }

  }
}

在HCLoad.Web項面前目今新建WebClientUpLoadStreamHandler.ashx

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

using System.IO; //由於要用到Stream

namespace HCLoad.Web
{
  public class WebClientUpLoadStreamHandler : IHttpHandler
  {

    public void ProcessRequest(HttpContext context)
    {
      //獲得上傳的數據流
      string fileNameStr = context.Request.QueryString["fileName"];
      Stream sr = context.Request.InputStream;
      try
      {
        string filename = "";

        filename = fileNameStr;

        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        //將以後數據流寫入辦事器端文件夾ClientBin下
        string targetPath = context.Server.MapPath("Pics/" + filename + ".jpg");
        using (FileStream fs = File.Create(targetPath, 4096))
        {
          while ((bytesRead = sr.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);
      }
      finally
      { sr.Dispose(); }

    }

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

}

新建download.ashx

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

namespace HCLoad.Web
{
  /// <summary>
  /// $codebehindclassname$ 的摘要解釋
  /// </summary>
  public class download : IHttpHandler
  {
    private long ChunkSize = 102400;//100K 每次讀取文件,只讀取100K,如許可以減緩辦事器的壓力

    public void ProcessRequest(HttpContext context)
    {
      //string fileName = "123.jpg";//客戶端保留的文件名
      String fileName = context.Request.QueryString["filename"]; 
      string filePath = context.Server.MapPath("Bubble.jpg");
      System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
      if (fileInfo.Exists == true)
      {
        byte[] buffer = new byte[ChunkSize];
        context.Response.Clear();
        System.IO.FileStream iStream = System.IO.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(ChunkSize));//讀取的年夜小
          context.Response.OutputStream.Write(buffer, 0, lengthRead);
          context.Response.Flush();
          dataLengthToRead = dataLengthToRead - lengthRead;
        }
        context.Response.Close();
        context.Response.End();
      }
      //context.Response.ContentType = "text/plain";
      //context.Response.Write("Hello World");
    }

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

參考:
http://www.cnblogs.com/wsdj-ittech/archive/2009/08/26/1554056.html
http://www.cnblogs.com/wsdj-ittech/archive/2009/08/25/1553534.html
http://www.cnblogs.com/wmt1708/archive/2009/03/07/1405009.html
http://topic.csdn.net/u/20090918/10/5e41ab52-f514-46b5-ae6a-d69ddb197213.html
http://www.cnblogs.com/wsdj-ittech/archive/2009/08/25/1553534.html
http://www.cnblogs.com/gwazy/archive/2009/04/02/1427781.html
http://www.cnblogs.com/ewyb/archive/2009/12/10/1621020.html
http://blog.csdn.net/emily1900/archive/2010/06/08/5655726.aspx

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved