Visual C#을 사용하여 웹 사이트에 파일 업로드

이 문서에서는 Microsoft Visual C#을 사용하여 파일을 업로드하는 방법을 설명합니다.

원래 제품 버전: Visual C#, ASP.NET, 인터넷 정보 서비스
원본 KB 번호: 816150

소개

이 단계별 문서에서는 로컬 하드 디스크 드라이브에서 웹 사이트로 기존 이미지 파일을 업로드하는 방법을 설명합니다. 입력 컨트롤은 로컬 컴퓨터에서 이미지를 업로드하는 데 사용됩니다. 업로드 중인 이 파일은 이미 업로드된 기존 파일을 덮어쓰지 않도록 서버에 대해 유효성을 검사합니다. 업로드된 파일이 서버에 있는 경우 유효성이 검사됩니다. 이 문서에서는 폼의 EncType 특성을 사용하여 기능을 구현합니다.

요구 사항

이 문서에서는 다음과 같은 topics 잘 알고 있다고 가정합니다.

  • 웹 애플리케이션
  • ASP.NET

다음 목록에서는 필요한 권장 소프트웨어 및 네트워크 인프라를 간략하게 설명합니다.

  • Visual C# .NET 또는 Visual C#
  • 인터넷 정보 서비스(IIS)

ASP.NET 웹 양식 만들기

  1. Visual Studio .NET 또는 Visual Studio를 시작합니다.

  2. 파일 메뉴에서 새로 만들기를 가리킨 다음 프로젝트를 클릭합니다.

    참고

    Visual Studio의 파일 메뉴에서 새로 만들기를 가리킨 다음 웹 사이트를 클릭합니다.

  3. 프로젝트 형식에서 Visual C# 프로젝트를 클릭합니다. 템플릿에서웹 애플리케이션 ASP.NET 클릭합니다.

    참고

    Visual Studio의 언어 오른쪽에서 Visual C#을 선택합니다. 템플릿에서ASP.NET 웹 사이트를 클릭합니다.

  4. 위치 상자에 다음 위치를 입력한 다음 확인을 클릭합니다.
    http://WebServerName/ApplicationName

    참고

    WebServerName 은 웹 서버 이름의 자리 표시자입니다. ApplicationName 은 애플리케이션 이름의 자리 표시자입니다.

    기본적으로 WebForm1.aspx 만들어집니다.

    참고

    Visual Studio에서 위치 오른쪽에서 HTTP를 선택한 다음, 를 입력합니다<http://WebServerName>.

  5. 보기 메뉴에서 HTML 원본을 클릭합니다.

    참고

    Visual Studio의 보기 메뉴에서 코드를 클릭합니다.

양식 특성 수정

WebForm1HTML 창에서 양식 태그를 다음으로 바꿉 있습니다.

<form id="Form1" method="post" runat="server" EncType="multipart/form-data" action="WebForm1.aspx">

특성은 EncType 게시되는 데이터의 형식을 지정합니다. 브라우저는 이 특성을 사용하여 서버에 게시된 정보를 인코딩합니다. 이 코드의 작업 특성은 페이지에서 요청을 처리할 것을 지정합니다. 기본적으로 폼의 메서드 특성은 트랜잭션에서 대량의 데이터를 보낼 수 있도록 게시하도록 설정됩니다.

입력 컨트롤을 추가하여 서버에 업로드할 파일을 지정합니다.

  1. WebForm1HTML 창에서 여는 태그와 닫는 <form> 태그 사이에 다음 코드를 추가합니다.

    <INPUT id="oFile" type="file" runat="server" NAME="oFile">
    

    이 입력 컨트롤은 서버에 업로드할 파일을 지정합니다.

  2. 컨트롤 앞에 텍스트 문자열을 추가하여 사용자에게 메시지를 표시할 수 있습니다. WebForm1HTML 창에서 입력 컨트롤 앞에 다음 텍스트를 입력합니다.

    서버에 업로드할 이미지 파일을 선택합니다.

단추 컨트롤 추가

  1. WebForm1HTML 창에서 입력 컨트롤 코드 다음에 여는 태그와 닫는 <form> 태그 사이에 다음 코드를 추가합니다.

    <asp:button id="btnUpload" type="submit" text="Upload" runat="server"></asp:button>
    
  2. 이 단추 컨트롤은 입력 컨트롤에서 지정한 파일을 업로드하는 데 사용됩니다.

출력을 표시하는 단일 레이블이 포함된 패널 컨트롤 만들기

WebForm1HTML 창에서 단추 컨트롤 코드 다음에 여는 태그와 닫는 <form> 태그 사이에 다음 코드를 추가합니다.

<asp:Panel ID="frmConfirmation" Visible="False" Runat="server">
    <asp:Label id="lblUploadResult" Runat="server"></asp:Label>
</asp:Panel>

이 코드는 파일 업로드가 성공했는지 여부를 나타내는 메시지를 표시하는 데 사용됩니다. 이 출력을 표시하기 위해 단일 레이블을 포함하는 패널 컨트롤이 만들어집니다.

Button Click 이벤트에서 파일 업로드

이 섹션의 코드는 로컬 파일 시스템에서 파일을 검색하고, 파일이 서버에 이미 있는지 확인한 다음, 웹 사이트에 파일을 업로드합니다. 이 코드를 추가하려면 다음 단계를 수행합니다.

  1. 이 문서의 단추 컨트롤 추가 섹션에서 만든 업로드 단추를 두 번 클릭하여 단추 컨트롤의 이벤트에 대한 Click 이벤트 처리기를 만듭니다.

  2. 코드 창의 맨 위에 다음 코드를 추가합니다.

    using System.IO;
    
  3. 업로드 단추의 Click 이벤트 처리기에 다음 코드를 추가합니다.

    string strFileName;
    string strFilePath;
    string strFolder;
    strFolder = Server.MapPath("./");
    // Retrieve the name of the file that is posted.
    strFileName = oFile.PostedFile.FileName;
    strFileName = Path.GetFileName(strFileName);
    if(oFile.Value != "")
    {
        // Create the folder if it does not exist.
        if(!Directory.Exists(strFolder))
        {
            Directory.CreateDirectory(strFolder);
        }
        // Save the uploaded file to the server.
        strFilePath = strFolder + strFileName;
        if(File.Exists(strFilePath))
        {
            lblUploadResult.Text = strFileName + " already exists on the server!";
        }
        else
        {
            oFile.PostedFile.SaveAs(strFilePath);
            lblUploadResult.Text = strFileName + " has been successfully uploaded.";
        }
    }
    else
    {
        lblUploadResult.Text = "Click 'Browse' to select the file to upload.";
    }
    // Display the result of the upload.
    frmConfirmation.Visible = true;
    
  4. 파일 메뉴에서 모두 저장을 클릭합니다.

업로드 작업이 작동하는지 확인합니다.

  1. 디버그 메뉴에서 시작을 클릭하여 애플리케이션을 빌드하고 실행합니다. 텍스트 상자와 명령 단추가 나타납니다.

  2. 텍스트 상자에 이미지 파일의 경로를 입력하거나 찾아보기를 클릭하여 로컬 컴퓨터에서 이미지 파일을 찾습니다.

  3. 업로드를 클릭하여 파일을 서버로 보냅니다. 파일이 고유하면 업로드에 성공했다는 메시지가 표시됩니다. 파일이 서버에 이미 있는 경우 적절한 메시지가 표시됩니다. 이 애플리케이션에서 업로드하는 파일은 로컬 하드 디스크의 위치에 C:\inetpub\wwwroot\ApplicationName 저장됩니다.

  4. 이 애플리케이션이 .NET Framework 작동하도록 하려면 ASPNET 사용자에 대한 모든 권한을 허용합니다. 이렇게 하려면 다음과 같이 하십시오.

    1. Windows Explorer 애플리케이션 폴더를 찾습니다. 경로는 입니다 C:\inetpub\wwwroot\ApplicationName.

    2. ApplicationName 폴더를 마우스 오른쪽 단추로 클릭한 다음 속성을 클릭합니다. ApplicationName 속성 대화 상자가 나타납니다.

    3. 보안 탭을 클릭합니다.

    4. 추가를 클릭합니다. 사용자 또는 그룹 선택 대화 상자가 나타납니다.

      참고

      Visual Studio에서 사용자, 컴퓨터 또는 그룹 선택 대화 상자가 나타납니다.

    5. 선택할 개체 이름 입력 상자에 ASPNET을 입력하고 확인을 클릭합니다.

    6. ApplicationName 속성 대화 상자의 그룹 또는 사용자 이름 목록에서 ASPNET 사용자를 클릭합니다.

    7. 허용에서 를 클릭하여 모든 권한 검사 상자를 선택한 다음 확인을 클릭합니다.

전체 코드 목록

  • WebForm1.aspx

    <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false"
       Inherits="Howto.WebForm1" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    <HTML>
       <HEAD>
          <title>WebForm1</title>
          <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
          <meta name="CODE_LANGUAGE" Content="C#">
          <meta name="vs_defaultClientScript" content="JavaScript">
          <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
       </HEAD>
       <body MS_POSITIONING="GridLayout">
          <form id="Form1" method="post" runat="server" EncType="multipart/form-data" action="WebForm1.aspx">
             Image file to upload to the server: <INPUT id="oFile" type="file" runat="server" NAME="oFile">
             <asp:button id="btnUpload" type="submit" text="Upload" runat="server"></asp:button>
             <asp:Panel ID="frmConfirmation" Visible="False" Runat="server">
                <asp:Label id="lblUploadResult" Runat="server"></asp:Label>
             </asp:Panel>
          </form>
       </body>
    </HTML>
    
  • WebForm1.aspx.cs

    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.IO;
    namespace **ApplicationName** {
    /// <summary>
    /// Summary description for WebForm1.
    /// </summary>
    public class WebForm1 : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.Button btnUpload;
        protected System.Web.UI.WebControls.Label lblUploadResult;
        protected System.Web.UI.WebControls.Panel frmConfirmation;
        protected System.Web.UI.HtmlControls.HtmlInputFile oFile;
    
        private void Page_Load(object sender, System.EventArgs e)
        {
        // Put user code to initialize the page here
        }
        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
        // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            InitializeComponent();
            base.OnInit(e);
        }
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click);
            this.Load += new System.EventHandler(this.Page_Load);
        }
        #endregion
    
        private void btnUpload_Click(object sender, System.EventArgs e)
        {
            string strFileName;
            string strFilePath;
            string strFolder;
            strFolder = Server.MapPath("./");
            // Get the name of the file that is posted.
            strFileName = oFile.PostedFile.FileName;
            strFileName = Path.GetFileName(strFileName);
            if(oFile.Value != "")
            {
                // Create the directory if it does not exist.
                if(!Directory.Exists(strFolder))
                {
                    Directory.CreateDirectory(strFolder);
                }
                // Save the uploaded file to the server.
                strFilePath = strFolder + strFileName;
                if(File.Exists(strFilePath))
                {
                    lblUploadResult.Text = strFileName + " already exists on the server!";
                }
                else
                {
                    oFile.PostedFile.SaveAs(strFilePath);
                    lblUploadResult.Text = strFileName + " has been successfully uploaded.";
                }
            }
            else
            {
                lblUploadResult.Text = "Click 'Browse' to select the file to upload.";
            }
            // Display the result of the upload.
            frmConfirmation.Visible = true;
        }
    }
    

참고

Visual Studio에서 생성된 코드는 Visual Studio .NET에서 생성된 코드와 다릅니다.

문제 해결

  1. 타임을 설치 한 경로 아래 의 CONFIG 폴더에 있는 컴퓨터에 있는Machine.config파일을 엽니다.
  2. <processModel>Machine.config 파일에서 섹션을 찾고, 및 password 특성을 W3wp.exe 또는 Aspnet_wp.exe 실행할 사용자의 이름과 암호로 변경 user 한 다음, Machine.config 파일을 저장합니다.
  3. CONFIG 폴더에 있는 임시 ASP.NET Files 폴더를 찾습니다. 임시 ASP.NET Files 폴더를 마우스 오른쪽 단추로 클릭한 다음 속성을 클릭합니다.
  4. 임시 ASP.NET 파일 속성 대화 상자에서 보안 탭을 클릭합니다.
  5. 고급을 클릭합니다.
  6. 임시 ASP.NET 파일의 Access Control 설정 대화 상자에서 추가를 클릭합니다.
  7. 대화 상자의 이름 상자에 사용자 이름을 입력하고 확인을 클릭합니다.
  8. 임시 ASP.NET 파일에 대한 권한 항목 대화 상자에서 사용자에게 전체 권한을 부여한 다음 확인을 클릭하여 임시 ASP.NET 파일 속성 대화 상자를 닫습니다.

참조