관리 메뉴

I LOVE EJ

ASP.NET 파일 업로드 본문

Web Development/.NET

ASP.NET 파일 업로드

BeOne 2007. 10. 15. 15:50
간단한 파일 업로드 만들기

■ ASP.NET 파일 업로드

ASP 개발자들이 놀라워 할 ASP.NET에서의 파일 업로드에 대해서 간단하게 알아봅시다. 기존 ASP에서는 파일 업로드를 위해 여러 가지 컴포넌트를 이용하여야 했습니다. 그러나 ASP.NET은 파일 저장에 관련된 여러 Namespace들을 지원하고 있기 때문에 코드에서 간단한 명령 몇줄만으로도 쉽게 클라이언트에서 업로드된 파일을 저장할 수 있습니다. 얼마나 놀랍습니까?

어떻게 ASP.NET을 이용하여 파일 저장을 처리하는지 지금부터 간단한 파일 업로드 예제를 통해서 알아보도록 합시다.

● fileupload.aspx


<%@ Import Namespace="System.IO" %>
<%@ page Language="C#" debug="true" %>

<html>
  <head>
    <title>간단한 FileUpload</title>
  </head>
  <script language="C#" runat="server">
    public void UploadFile(object sender, EventArgs E)
    {
      //파일이 첨부되었는지 확인
      if(pdsFile.PostedFile != null)
      {
        try
        {
          //파일경로, 파일명 가져오기
          string pdsfilename = pdsFile.PostedFile.FileName;
          int i = pdsfilename.LastIndexOf("\\");
          string newname = pdsfilename.Substring(i);

          //서버에 파일을 저장, \\는 역슬래쉬의 excape 문자입니다.
          pdsFile.PostedFile.SaveAs("d:\\works\\net\\aspnet\\fileupload\\"+newname);

          //업로드 한 파일의 여러 가지 정보 수집
          pdsname.Text = pdsFile.PostedFile.FileName;
          pdsenc.Text = pdsFile.PostedFile.ContentType;
          pdssize.Text = (pdsFile.PostedFile.ContentLength/1024).ToString() + "KB";
        }
        catch (Exception exc)
        {
          Response.Write("에러가 발생하였습니다 : " + exc.ToString());
        }

      }
    }
  </script>
  <body>
    <center>
    <h3> ASP.NET 파일 업로드 </h3>

    <form id="uploderform" method="post" action="Fileupload.aspx" enctype="multipart/form-data" runat="server">
    <table border="0" align=center>
      <tr>
        <td align=center><b>업로드 할 파일을 선택해 주세요.</b></td>
      </tr>
      <tr>
        <td>
          <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="*" ControlToValidate="pdsFile"></asp:RequiredFieldValidator>
          <input type="file" id="pdsFile" size="40" runat="server">
          <input type="button" value="Upload" OnServerClick="UploadFile" runat="server" >
        </td>
      </tr>
    </table>
    </form>

    <br><br>
    <table cellspacing="2">
      <tr>
        <td><b>업로드 파일정보</b></td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td>파일명 :</td>
        <td><asp:label id="pdsname" text="" runat="server" /></td>
      </tr>
      <tr>
        <td>파일 인코딩 :</td>
        <td><asp:label id="pdsenc" runat="server" /></td>
      </tr>
      <tr>
        <td>파일 크기 :</td>
        <td><asp:label id="pdssize" runat="server" /></td>
      </tr>
    </table>
    <br><br>

    </center>
  </body>
</html>


[이 코드를 복사하여 실행하지 마십시오. 에러 발생합니다. 첨부파일 참고]


[그림]fileupload.aspx 실행결과

클라이언트의 파일을 업로드하여 실행결과를 확인해 보자. 다음의 결과가 출력될 것이다.


[그림] fileupload.aspx 파일 업로드 결과