실습 : 방명록

2009. 12. 16. 20:44

보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.



- 사용자의 로컬 파일 선택 가능
- 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
:




- 웹브라우저 쿠키와 비슷하게 실버라이트에서 사용하는 사용자 컴퓨터에 저장되는 임시 데이터 저장 공간

- 1~50MB 정도의 공간을 사용 가능
    - 사용자의 허락하에 50MB 사용 가능

- 실버라이트 응용 프로그램의 간단한 상태 관리를 위해서 주로 사용

- 실버라이트에서는 '세션', '쿠키'를 사용할 수 없다.








[MainPage.xaml]


<UserControl x:Class="RiaIsolatedStorage.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">

        <StackPanel Orientation="Horizontal">

            <TextBlock Text="마지막 방문 시간 : " />

            <TextBlock x:Name="lblLastVisit" />

        </StackPanel>

        <StackPanel>

            <Button x:Name="btnAddSpace" Content="저장 공간 늘리기" />

        </StackPanel>

    </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.IsolatedStorage;

 

namespace RiaIsolatedStorage

{

    public partial class MainPage : UserControl

    {

        public MainPage()

        {

            InitializeComponent();

            this.Loaded += new RoutedEventHandler(MainPage_Loaded);

            btnAddSpace.Click += new RoutedEventHandler(btnAddSpace_Click);

        }

        void btnAddSpace_Click(object sender, RoutedEventArgs e)

        {

            // 저장 공간 늘리기

            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication(); // 현재 공간 가져오기

            MessageBox.Show("현재 : " + isf.AvailableFreeSpace.ToString()); // 현재값 출력

            long newSize = isf.AvailableFreeSpace + 1048576;

            isf.IncreaseQuotaTo(newSize);

        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)

        {

            // 마지막 방문 정보가 격리 저장소에 들어있으면 출력, 새롭게 등록

            IsolatedStorageSettings iss = IsolatedStorageSettings.ApplicationSettings;

            if (iss.Contains("keyLast"))

            {

                lblLastVisit.Text = iss["keyLast"].ToString(); // 이전에 기록된 출력

                SetLastVisit(iss);

            }

            else

            {

                SetLastVisit(iss); // 처음 방문 또는 이전 방문 정보가 제거되었다면...

            }

        }

        private static void SetLastVisit(IsolatedStorageSettings iss)

        {

            iss["keyLast"] = DateTime.Now; // 현재시간으로 재설정

        }

    }

}

 

 


















Posted by holland14
: