- 사용자의 로컬 파일 선택 가능
- Stream 클래스를 통해서 응용 프로그램에서 사용 가능
- 다중 파일 선택 및 확장자 제한 가능
- 주 사용분야 :
    - 파일업로드 : WebClient 또는 HttpWebRequest 사용
    - 로컬 이미지 보기 : <Image /> 사용
    - 로컬 미디어 실행 : <MediaElement /> 사용







"파일 업로드" 실습을 하기 위하여 아래그림과 같이 '솔루션 탐색기'에서 "Files"라는 이름의 '새 폴더'를 추가한다. 그리고 아래그림과 같이 '새 항목 추가'로 "FileUploadHandler.ashx"라는 이름으로 '제네릭 처리기'형식의 파일을 하나 추가한다.


















[MainPage.xaml]


<UserControl x:Class="RiaOpenFileDialog.MainPage"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    mc:Ignorable="d"

    d:DesignHeight="300" d:DesignWidth="400">

 

    <Grid x:Name="LayoutRoot" Background="White">

        <Button x:Name="btnFileUpload" Content="파일 업로드" Width="100" Height="30" />

    </Grid>

</UserControl>

 

 








[MainPage.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.IO;

 

namespace RiaOpenFileDialog

{

    public partial class MainPage : UserControl

    {

        public MainPage()

        {

            InitializeComponent();

            btnFileUpload.Click += new RoutedEventHandler(btnFileUpload_Click);

        }

 

        void btnFileUpload_Click(object sender, RoutedEventArgs e)

        {

            OpenFileDialog ofd = new OpenFileDialog(); // 파일 선택

            ofd.Filter = "모든 파일|*.*";

            ofd.Multiselect = false;

 

            bool? r = ofd.ShowDialog();

            if (r.HasValue && r == true)

            {

                this.btnFileUpload.IsEnabled = false; // 업로드되는 동안 비활성화

                UriBuilder url = new UriBuilder("http://localhost:2654/FileUploadHandler.ashx");

                url.Query = string.Format("FileName={0}", ofd.File.Name);

 

                Stream stream = ofd.File.OpenRead(); // 파일을 스트림 개체로 읽어서,

                WebClient client = new WebClient(); // 원격지 서버로 데이터 전송

 

                client.OpenWriteCompleted += delegate(object ss, OpenWriteCompletedEventArgs ee)

                {

                    byte[] buffer = new byte[4096]; // 4096 바이트 단위로 서버로 전송(제네릭 처리기)

                    int len = stream.Read(buffer, 0, buffer.Length);

 

                    while (len > 0)

                    {

                        ee.Result.Write(buffer, 0, len);

 

                        len = stream.Read(buffer, 0, buffer.Length);

                    }

                    ee.Result.Close();

                    stream.Close();

                    this.btnFileUpload.IsEnabled = true; // 활성화

                }; // end OpenWriteCompleted

 

                client.OpenWriteAsync(url.Uri); // 업로드 진행

            } // end if

        } // end Click

    }

}

 

 









[FileUploadHandler.ashx.cs]


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.IO;

 

namespace RiaOpenFileDialog.Web

{

    /// <summary>

    /// Summary description for FileUploadHandler

    /// </summary>

    public class FileUploadHandler : IHttpHandler

    {

 

        public void ProcessRequest(HttpContext context)

        {

            string strFileName = context.Request.QueryString["FileName"]; // 실버라이트에서 넘겨줄 이름

            string strDir = String.Format("{0}/{1}", context.Server.MapPath("~/Files"), strFileName); // 경로

            // 4096바이트 단위로 끊어서 저장

            using (FileStream fs = File.Create(strDir))

            {

                byte[] buffer = new byte[4096];

                int len = context.Request.InputStream.Read(buffer, 0, buffer.Length);

 

                while (len > 0)

                {

                    fs.Write(buffer, 0, len); // 버퍼에 담긴 값을 해당 경로에 저장

                    len = context.Request.InputStream.Read(buffer, 0, buffer.Length);

                }

            }

        }

 

        public bool IsReusable

        {

            get

            {

                return false;

            }

        }

    }

}

 










[실행결과]


















아래그림과 같이 "솔루션 탐색기"에서 "모든 파일 표시"버튼을 마우스로 클릭해보면(새로 고침 버튼도 클릭) 아래와 같이 해당 파일이 업로드 된 것을 확인할 수 있다.












Posted by holland14
: