정보 보관 ver1.0

FileUpload 클래스

James Wetzel 2010. 11. 11. 13:24

사용자가 서버에 업로드할 파일을 선택하는 데 사용할 수 있는 TextBox 컨트롤과 찾아보기 단추를 표시합니다.

  • 첫 번째 예제에서는 코드에 지정된 경로에 파일을 저장하는 FileUpload 컨트롤을 만드는 방법을 보여 줍니다.

  • 두 번째 예제에서는 응용 프로그램의 파일 시스템에서 지정된 디렉터리에 파일을 저장하는 FileUpload 컨트롤을 만드는 방법을 보여 줍니다.

  • 세 번째 예제에서는 지정된 경로에 파일을 저장하고 업로드할 수 있는 파일 크기를 제한하는 FileUpload 컨트롤을 만드는 방법을 보여 줍니다.

  • 네 번째 예제에서는 지정된 경로에 파일을 저장하고 파일 이름 확장명이 .doc 또는 .xls인 파일의 업로드만 허용하는 FileUpload 컨트롤을 만드는 방법을 보여 줍니다.

    메모리 제한

    서비스 거부 공격을 방지할 수 있는 한 가지 방법은 FileUpload 컨트롤을 사용하여 업로드할 수 있는 파일의 크기를 제한하는 것입니다. 업로드될 것으로 예상되는 파일의 형식에 적절한 크기 한계를 설정해야 합니다. 기본 크기 제한은 4096KB(4MB)입니다. httpRuntime 요소의 maxRequestLength 특성을 설정하면 보다 큰 파일의 업로드를 허용할 수 있습니다. 전체 응용 프로그램에 대해 허용되는 최대 파일 크기를 늘리려면 Web.config 파일에서 maxRequestLength 특성을 설정합니다. 지정된 페이지에 대해 허용되는 최대 파일 크기를 늘리려면 Web.config 파일의 location 요소 내에 maxRequestLength 특성을 설정합니다. 예제를 보려면 location 요소(ASP.NET 설정 스키마)을 참조하십시오.

    사용자가 큰 파일을 업로드할 때 다음 오류 메시지가 나타날 수도 있습니다.

    aspnet_wp.exe (PID: 1520) was recycled because memory consumption exceeded 460 MB (60 percent of available RAM).

    사용자에게 이 오류 메시지가 나타나면 응용 프로그램의 Web.config 파일 요소에서 processModelmemoryLimit 특성 값을 늘립니다. memoryLimit 특성은 작업자 프로세스에서 사용할 수 있는 최대 메모리 양을 지정합니다. 작업자 프로세스에서 memoryLimit 양을 초과하면 해당 프로세스를 대체할 새 프로세스가 만들어지고 현재 요청이 모두 새 프로세스에 다시 할당됩니다.

    요청이 처리되는 동안 업로드할 파일을 임시로 메모리에 저장할지 아니면 서버에 저장할지를 제어하려면 httpRuntime 요소의 requestLengthDiskThreshold 특성을 설정합니다. 이 특성을 사용하면 입력 스트림 버퍼의 크기를 관리할 수 있습니다. 기본값은 256바이트입니다. 이 특성에 지정한 값이 maxRequestLength 특성에 지정한 값을 초과하면 안 됩니다.


<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

  protected void UploadButton_Click(object sender, EventArgs e)
  {
    // Specify the path on the server to
    // save the uploaded file to.
    String savePath = @"c:\temp\uploads\";

    // Before attempting to perform operations
    // on the file, verify that the FileUpload
    // control contains a file.
    if (FileUpload1.HasFile)
    {
      // Get the name of the file to upload.
      String fileName = FileUpload1.FileName;

      // Append the name of the file to upload to the path.
      savePath += fileName;


      // Call the SaveAs method to save the
      // uploaded file to the specified path.
      // This example does not perform all
      // the necessary error checking.              
      // If a file with the same name
      // already exists in the specified path, 
      // the uploaded file overwrites it.
      FileUpload1.SaveAs(savePath);

      // Notify the user of the name of the file
      // was saved under.
      UploadStatusLabel.Text = "Your file was saved as " + fileName;
    }
    else
    {     
      // Notify the user that a file was not uploaded.
      UploadStatusLabel.Text = "You did not specify a file to upload.";
    }

  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>FileUpload Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       <h4>Select a file to upload:</h4>

       <asp:FileUpload id="FileUpload1"                
           runat="server">
       </asp:FileUpload>

       <br /><br />

       <asp:Button id="UploadButton"
           Text="Upload file"
           OnClick="UploadButton_Click"
           runat="server">
       </asp:Button>   

       <hr />

       <asp:Label id="UploadStatusLabel"
           runat="server">
       </asp:Label>       
    </div>
    </form>
</body>
</html>





<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    protected void UploadButton_Click(object sender, EventArgs e)
    {
        // Save the uploaded file to an "Uploads" directory
        // that already exists in the file system of the
        // currently executing ASP.NET application. 
        // Creating an "Uploads" directory isolates uploaded
        // files in a separate directory. This helps prevent
        // users from overwriting existing application files by
        // uploading files with names like "Web.config".
        string saveDir = @"\Uploads\";

        // Get the physical file system path for the currently
        // executing application.
        string appPath = Request.PhysicalApplicationPath;

        // Before attempting to save the file, verify
        // that the FileUpload control contains a file.
        if (FileUpload1.HasFile)
        {
            string savePath = appPath + saveDir +
                Server.HtmlEncode(FileUpload1.FileName);

            // Call the SaveAs method to save the
            // uploaded file to the specified path.
            // This example does not perform all
            // the necessary error checking.              
            // If a file with the same name
            // already exists in the specified path, 
            // the uploaded file overwrites it.
            FileUpload1.SaveAs(savePath);

            // Notify the user that the file was uploaded successfully.
            UploadStatusLabel.Text = "Your file was uploaded successfully.";

        }
        else
        {
            // Notify the user that a file was not uploaded.
            UploadStatusLabel.Text = "You did not specify a file to upload.";  
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>FileUpload Class Example</title>
</head>
<body>
    <h3>FileUpload Class Example: Save To Application Directory</h3>
    <form id="form1" runat="server">
    <div>
       <h4>Select a file to upload:</h4>

       <asp:FileUpload id="FileUpload1"                
           runat="server">
       </asp:FileUpload>

       <br/><br/>

       <asp:Button id="UploadButton"
           Text="Upload file"
           OnClick="UploadButton_Click"
           runat="server">
       </asp:Button>   

       <hr />

       <asp:Label id="UploadStatusLabel"
           runat="server">
       </asp:Label>          
    </div>
    </form>
</body>
</html>




<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    protected void UploadButton_Click(object sender, EventArgs e)
    {
        // Specify the path on the server to
        // save the uploaded file to.
        string savePath = @"c:\temp\uploads\";

        // Before attempting to save the file, verify
        // that the FileUpload control contains a file.
        if (FileUpload1.HasFile)
        {               
            // Get the size in bytes of the file to upload.
            int fileSize = FileUpload1.PostedFile.ContentLength;

            // Allow only files less than 2,100,000 bytes (approximately 2 MB) to be uploaded.
            if (fileSize < 2100000)
            {

                // Append the name of the uploaded file to the path.
                savePath += Server.HtmlEncode(FileUpload1.FileName);

                // Call the SaveAs method to save the
                // uploaded file to the specified path.
                // This example does not perform all
                // the necessary error checking.              
                // If a file with the same name
                // already exists in the specified path, 
                // the uploaded file overwrites it.
                FileUpload1.SaveAs(savePath);

                // Notify the user that the file was uploaded successfully.
                UploadStatusLabel.Text = "Your file was uploaded successfully.";
            }
            else
            {
                // Notify the user why their file was not uploaded.
                UploadStatusLabel.Text = "Your file was not uploaded because " +
                                         "it exceeds the 2 MB size limit.";
            }
        }  
        else
        {
            // Notify the user that a file was not uploaded.
            UploadStatusLabel.Text = "You did not specify a file to upload.";
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>FileUpload Class Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       <h4>Select a file to upload:</h4>

       <asp:FileUpload id="FileUpload1"                
           runat="server">
       </asp:FileUpload>

       <br/><br/>

       <asp:Button id="UploadButton"
           Text="Upload file"
           OnClick="UploadButton_Click"
           runat="server">
       </asp:Button>

       <hr />

       <asp:Label id="UploadStatusLabel"
           runat="server">
       </asp:Label>

    </div>
    </form>
</body>
</html>





<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    protected void UploadBtn_Click(object sender, EventArgs e)
    {
        // Specify the path on the server to
        // save the uploaded file to.
        string savePath = @"c:\temp\uploads";

        // Before attempting to save the file, verify
        // that the FileUpload control contains a file.
        if (FileUpload1.HasFile)
        {
            // Get the name of the file to upload.
            string fileName = Server.HtmlEncode(FileUpload1.FileName);

            // Get the extension of the uploaded file.
            string extension = System.IO.Path.GetExtension(fileName);

            // Allow only files with .doc or .xls extensions
            // to be uploaded.
            if ((extension == ".doc") || (extension == ".xls"))
            {
                // Append the name of the file to upload to the path.
                savePath += fileName;

                // Call the SaveAs method to save the
                // uploaded file to the specified path.
                // This example does not perform all
                // the necessary error checking.              
                // If a file with the same name
                // already exists in the specified path, 
                // the uploaded file overwrites it.
                FileUpload1.SaveAs(savePath);

                // Notify the user that their file was successfully uploaded.
                UploadStatusLabel.Text = "Your file was uploaded successfully.";
            }
            else
            {
                // Notify the user why their file was not uploaded.
                UploadStatusLabel.Text = "Your file was not uploaded because " +
                                         "it does not have a .doc or .xls extension.";
            }

        }

    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>FileUpload Class Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h4>Select a file to upload:</h4>

        <asp:FileUpload id="FileUpload1"                
            runat="server">
        </asp:FileUpload>

        <br/><br/>

        <asp:Button id="UploadBtn"
            Text="Upload file"
            OnClick="UploadBtn_Click"
            runat="server">
        </asp:Button>   

        <hr />

        <asp:Label id="UploadStatusLabel"
            runat="server">
        </asp:Label>    
    </div>
    </form>
</body>
</html>


자료 출처<MSDN> : http://msdn.microsoft.com/ko-kr/library/system.web.ui.webcontrols.fileupload(v=VS.100).aspx#memory_limitations

728x90
반응형