最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Silverlight文件上傳下載實(shí)現(xiàn)方法(下載保存)

 更新時(shí)間:2015年11月08日 14:46:36   投稿:mdxy-dxy  
這篇文章主要介紹了Silverlight文件上傳下載實(shí)現(xiàn)方法(下載保存) ,需要的朋友可以參考下

search了非常多的文章,總算勉強(qiáng)實(shí)現(xiàn)了。有許多不完善的地方。


在HCLoad.Web項(xiàng)目下新建目錄Pics復(fù)制一張圖片到根目錄下。

圖片名: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="下載進(jìn)度" 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; //因?yàn)橐褂肂itmapImage
using System.IO; //因?yàn)橐褂肧tream

namespace HCLoad
{
  public partial class UC_UpDown : UserControl
  {
    //1、WebClient 對(duì)象一次只能啟動(dòng)一個(gè)請(qǐng)求。如果在一個(gè)請(qǐng)求完成(包括出錯(cuò)和取消)前,即IsBusy為true時(shí),進(jìn)行第二個(gè)請(qǐng)求,則第二個(gè)請(qǐng)求將會(huì)拋出 NotSupportedException 類型的異常
    //2、如果 WebClient 對(duì)象的 BaseAddress 屬性不為空,則 BaseAddress 與 URI(相對(duì)地址) 組合在一起構(gòu)成絕對(duì) URI
    //3、WebClient 類的 AllowReadStreamBuffering 屬性:是否對(duì)從 Internet 資源接收的數(shù)據(jù)做緩沖處理。默認(rèn)值為true,將數(shù)據(jù)緩存在客戶端內(nèi)存中,以便隨時(shí)被應(yīng)用程序讀取



    //獲取選定圖片信息
    System.IO.FileInfo fileinfo;
    public UC_UpDown()
    {
      InitializeComponent();
    }
    #region 下載圖片
    private void btnDownload_Click(object sender, RoutedEventArgs e)
    {
      //向指定的Url發(fā)送下載流數(shù)據(jù)請(qǐng)求 
      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 - 該異步操作期間是否發(fā)生了錯(cuò)誤
      //OpenReadCompletedEventArgs.Cancelled - 該異步操作是否已被取消
      //OpenReadCompletedEventArgs.Result - 下載后的 Stream 類型的數(shù)據(jù)
      //OpenReadCompletedEventArgs.UserState - 用戶標(biāo)識(shí)

      if (e.Error != null)
      {
        MessageBox.Show(e.Error.ToString());
        return;
      }
      if (e.Cancelled != true)
      {
        //獲取下載的流數(shù)據(jù)(在此處是圖片數(shù)據(jù))并顯示在圖片控件中
        //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 - 當(dāng)前收到的字節(jié)數(shù)
      //DownloadProgressChangedEventArgs.TotalBytesToReceive - 總共需要下載的字節(jié)數(shù)
      //DownloadProgressChangedEventArgs.UserState - 用戶標(biāo)識(shí)

      this.tbMsgString.Text = string.Format("完成百分比:{0} 當(dāng)前收到的字節(jié)數(shù):{1} 資料大?。簕2} ",
       e.ProgressPercentage.ToString() + "%",
       e.BytesReceived.ToString(),
       e.TotalBytesToReceive.ToString());

    }

    #endregion

    #region 上傳圖片
    private void btnUpLoad_Click(object sender, RoutedEventArgs e)
    {
      /**/
      /*
     *   OpenWriteCompleted - 在打開用于上傳的流完成時(shí)(包括取消操作及有錯(cuò)誤發(fā)生時(shí))所觸發(fā)的事件
     *   WriteStreamClosed - 在寫入數(shù)據(jù)流的異步操作完成時(shí)(包括取消操作及有錯(cuò)誤發(fā)生時(shí))所觸發(fā)的事件
     *   UploadProgressChanged - 上傳數(shù)據(jù)過(guò)程中所觸發(fā)的事件。如果調(diào)用 OpenWriteAsync() 則不會(huì)觸發(fā)此事件
     *   Headers - 與請(qǐng)求相關(guān)的的標(biāo)頭的 key/value 對(duì)**
     *   OpenWriteAsync(Uri address, string method, Object userToken) - 打開流以使用指定的方法向指定的 URI 寫入數(shù)據(jù)
     *     Uri address - 接收上傳數(shù)據(jù)的 URI
     *     string method - 所使用的 HTTP 方法(POST 或 GET)
     *     Object userToken - 需要上傳的數(shù)據(jù)流
     */


      OpenFileDialog openFileDialog = new OpenFileDialog()
      { //彈出打開文件對(duì)話框要求用戶自己選擇在本地端打開的圖片文件
        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 把圖片上傳到服務(wù)器上

          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("請(qǐng)選取想要上載的圖片!!!");
        }
      }

    }



    void webclient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
    {

      //將圖片數(shù)據(jù)流發(fā)送到服務(wù)器上

      // e.UserState - 需要上傳的流(客戶端流)
      Stream clientStream = e.UserState as Stream;
      // e.Result - 目標(biāo)地址的流(服務(wù)端流)
      Stream serverStream = e.Result;
      byte[] buffer = new byte[4096];
      int readcount = 0;
      // clientStream.Read - 將需要上傳的流讀取到指定的字節(jié)數(shù)組中
      while ((readcount = clientStream.Read(buffer, 0, buffer.Length)) > 0)
      {
        // serverStream.Write - 將指定的字節(jié)數(shù)組寫入到目標(biāo)地址的流
        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)
    {
      //這種方法搞不定,好像提示跨域操作。
      //提示:錯(cuò)誤:Unhandled Error in Silverlight Application 跨線程訪問(wèn)無(wú)效。
      //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);

      //通過(guò)調(diào)用js代碼下載,比較簡(jiǎn)單。
      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項(xiàng)目下新建WebClientUpLoadStreamHandler.ashx

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

using System.IO; //因?yàn)橐玫絊tream

namespace HCLoad.Web
{
  public class WebClientUpLoadStreamHandler : IHttpHandler
  {

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

        filename = fileNameStr;

        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        //將當(dāng)前數(shù)據(jù)流寫入服務(wù)器端文件夾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("上傳失敗, 錯(cuò)誤信息:" + 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$ 的摘要說(shuō)明
  /// </summary>
  public class download : IHttpHandler
  {
    private long ChunkSize = 102400;//100K 每次讀取文件,只讀取100K,這樣可以緩解服務(wù)器的壓力

    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

相關(guān)文章

  • C#橋接模式完整實(shí)例

    C#橋接模式完整實(shí)例

    這篇文章主要介紹了C#橋接模式,以實(shí)例形式較為詳細(xì)的分析了C#橋接模式的實(shí)現(xiàn)原理與相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-07-07
  • C#中調(diào)整圖像大小的步驟詳解

    C#中調(diào)整圖像大小的步驟詳解

    這篇文章主要介紹了C#中調(diào)整圖像大小的步驟詳解,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-05-05
  • C#操作SQLite數(shù)據(jù)庫(kù)幫助類詳解

    C#操作SQLite數(shù)據(jù)庫(kù)幫助類詳解

    這篇文章主要介紹了C#操作SQLite數(shù)據(jù)庫(kù)幫助類,詳細(xì)分析了C#針對(duì)sqlite數(shù)據(jù)庫(kù)的連接、查詢、分頁(yè)等各種常見操作的實(shí)現(xiàn)與封裝技巧,需要的朋友可以參考下
    2017-07-07
  • C#實(shí)現(xiàn)讀寫ini配置文件的方法詳解

    C#實(shí)現(xiàn)讀寫ini配置文件的方法詳解

    這篇文章主要為大家詳細(xì)介紹了如何利用C#實(shí)現(xiàn)讀寫ini配置文件操作,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)C#有一定的幫助,感興趣的小伙伴可以了解一下
    2022-12-12
  • c#的dataset離線數(shù)據(jù)集示例

    c#的dataset離線數(shù)據(jù)集示例

    這篇文章主要介紹了c#的dataset離線數(shù)據(jù)集示例,需要的朋友可以參考下
    2014-04-04
  • C#實(shí)現(xiàn)飛行棋(Winform)

    C#實(shí)現(xiàn)飛行棋(Winform)

    這篇文章主要為大家詳細(xì)介紹了基于Winform框架的飛行棋,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-02-02
  • 使用Spire.Barcode程序庫(kù)生成二維碼的實(shí)例解析

    使用Spire.Barcode程序庫(kù)生成二維碼的實(shí)例解析

    這篇文章主要介紹了使用Spire.Barcode程序庫(kù)生成二維碼的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下
    2016-12-12
  • C# 控件屬性和InitializeComponent()關(guān)系案例詳解

    C# 控件屬性和InitializeComponent()關(guān)系案例詳解

    這篇文章主要介紹了C# 控件屬性和InitializeComponent()關(guān)系案例詳解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • C#使用IHttpModule接口修改http輸出的方法

    C#使用IHttpModule接口修改http輸出的方法

    這篇文章主要介紹了C#使用IHttpModule接口修改http輸出的方法,涉及C#操作IHttpModule接口的相關(guān)技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下
    2015-05-05
  • C#打開php鏈接傳參然后接收返回值的關(guān)鍵代碼

    C#打開php鏈接傳參然后接收返回值的關(guān)鍵代碼

    這篇文章主要介紹了C#打開php鏈接傳參然后接收返回值的關(guān)鍵代碼,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下
    2016-08-08

最新評(píng)論

溧阳市| 社旗县| 霸州市| 洱源县| 祁阳县| 澄江县| 白城市| 赤壁市| 延长县| 偃师市| 武隆县| 深水埗区| 徐闻县| 元阳县| 德州市| 佛冈县| 中方县| 连江县| 洪湖市| 闽侯县| 荥阳市| 和林格尔县| 海宁市| 商水县| 永泰县| 麻阳| 长治市| 镇原县| 麻栗坡县| 景谷| 图片| 商南县| 瑞丽市| 漳浦县| 武川县| 申扎县| 金乡县| 宿州市| 陵川县| 从化市| 满城县|