다음을 통해 공유


FileUpload.SaveAs(String) 메서드

정의

업로드된 파일의 내용을 웹 서버의 지정된 경로에 저장합니다.

public:
 void SaveAs(System::String ^ filename);
public void SaveAs(string filename);
member this.SaveAs : string -> unit
Public Sub SaveAs (filename As String)

매개 변수

filename
String

업로드된 파일을 저장할 서버 위치의 전체 경로를 지정하는 문자열입니다.

예외

filename 가 전체 경로가 아닙니다.

예제

다음 예제에서는 오류 검사를 수행하는 컨트롤을 FileUpload 만드는 방법을 보여 줍니다. 파일을 저장 HasFile 하기 전에 업로드할 파일이 있는지 확인하기 위해 메서드가 호출됩니다. 또한 File.Exists 동일한 이름을 가진 파일이 경로에 이미 있는지 확인하기 위해 메서드가 호출됩니다. 이 경우 업로드할 파일의 이름 앞에는 메서드가 호출되기 전에 숫자가 접두사로 SaveAs 추가됩니다. 이렇게 하면 기존 파일을 덮어쓰지 않습니다.

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>FileUpload.SaveAs Method Example</title>
<script runat="server">
        
    protected void  UploadButton_Click(object sender, EventArgs e)
    {
        // Before attempting to save the file, verify
        // that the FileUpload control contains a file.
        if (FileUpload1.HasFile) 
          // Call a helper method routine to save the file.
          SaveFile(FileUpload1.PostedFile);
        else
          // Notify the user that a file was not uploaded.
          UploadStatusLabel.Text = "You did not specify a file to upload.";
    }
            
      void SaveFile(HttpPostedFile file)
      {            
        // Specify the path to save the uploaded file to.
        string savePath = "c:\\temp\\uploads\\";
            
        // Get the name of the file to upload.
        string fileName = FileUpload1.FileName;
            
        // Create the path and file name to check for duplicates.
        string pathToCheck = savePath + fileName;
        
        // Create a temporary file name to use for checking duplicates.
        string tempfileName = "";
            
        // Check to see if a file already exists with the
        // same name as the file to upload.        
        if (System.IO.File.Exists(pathToCheck)) 
        {
          int counter = 2;
          while (System.IO.File.Exists(pathToCheck))
          {
            // if a file with this name already exists,
            // prefix the filename with a number.
            tempfileName = counter.ToString() + fileName;
            pathToCheck = savePath + tempfileName;
            counter ++;
          }
          
          fileName = tempfileName;
          
          // Notify the user that the file name was changed.
          UploadStatusLabel.Text = "A file with the same name already exists." + 
              "<br />Your file was saved as " + fileName;
        }
        else
        {
          // Notify the user that the file was saved successfully.
          UploadStatusLabel.Text = "Your file was uploaded successfully.";
        }

        // 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 directory.
        FileUpload1.SaveAs(savePath);
            
      }
        
</script>

</head>
<body>

    <h3>FileUpload.SaveAs Method Example</h3>

    <form id="Form1" runat="server">
   
        <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>   
         
    </form>

</body>
</html>
<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>FileUpload.SaveAs Method Example</title>
<script runat="server">
        
      Sub UploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            
        ' Before attempting to save the file, verify
        ' that the FileUpload control contains a file.
        If (FileUpload1.HasFile) Then
          ' Call a helper method routine to save the file.
          SaveFile(FileUpload1.PostedFile)
        Else
          ' Notify the user that a file was not uploaded.
          UploadStatusLabel.Text = "You did not specify a file to upload."
        End If

      End Sub
        
      Sub SaveFile(ByVal file As HttpPostedFile)
            
        ' Specify the path to save the uploaded file to.
        Dim savePath As String = "c:\temp\uploads\"
            
        ' Get the name of the file to upload.
        Dim fileName As String = FileUpload1.FileName
            
        ' Create the path and file name to check for duplicates.
        Dim pathToCheck As String = savePath + fileName
        
        ' Create a temporary file name to use for checking duplicates.
        Dim tempfileName As String
            
        ' Check to see if a file already exists with the
        ' same name as the file to upload.        
        If (System.IO.File.Exists(pathToCheck)) Then
          Dim counter As Integer = 2
          While (System.IO.File.Exists(pathToCheck))
            ' If a file with this name already exists,
            ' prefix the filename with a number.
            tempfileName = counter.ToString() + fileName
            pathToCheck = savePath + tempfileName
            counter = counter + 1
          End While
          
          fileName = tempfileName
          
          ' Notify the user that the file name was changed.
          UploadStatusLabel.Text = "A file with the same name already exists." + "<br />" + _
                                   "Your file was saved as " + fileName
          
        Else
          
          ' Notify the user that the file was saved successfully.
          UploadStatusLabel.Text = "Your file was uploaded successfully."
          
        End If

        ' 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 directory.
        FileUpload1.SaveAs(savePath)
            
      End Sub
        
  </script>

</head>
<body>

    <h3>FileUpload.SaveAs Method Example</h3>

    <form id="Form1" runat="server">
   
        <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>   
         
    </form>

</body>
</html>

설명

이 메서드는 SaveAs 업로드된 파일의 내용을 웹 서버의 지정된 경로에 저장합니다.

사용자가 업로드할 파일을 선택한 후에는 FileUpload 컨트롤이 서버에 파일을 자동으로 저장하지 않습니다. 사용자가 지정된 파일을 제출할 수 있도록 컨트롤 또는 메커니즘을 명시적으로 제공해야 합니다. 예를 들어 사용자가 파일을 업로드하기 위해 클릭하는 단추를 제공할 수 있습니다. 지정한 파일을 저장하기 위해 작성하는 코드는 서버의 지정된 경로에 파일 내용을 저장하는 메서드를 호출 SaveAs 해야 합니다. 일반적으로 SaveAs 메서드는 서버에 다시 게시를 발생 하는 이벤트에 대 한 이벤트 처리 메서드에서 호출 됩니다. 예를 들어 파일을 제출하는 단추를 제공하는 경우 파일을 서버에 저장하는 코드가 클릭 이벤트에 대한 이벤트 처리 메서드 내에 포함될 수 있습니다.

메서드를 SaveAs 호출할 때 업로드된 파일을 저장할 서버에서 디렉터리의 전체 경로를 지정해야 합니다. 애플리케이션 코드 HttpException 에서 경로를 명시적으로 지정하지 않으면 사용자가 파일 업로드를 시도할 때 예외가 throw됩니다. 이 동작은 사용자가 업로드하는 파일을 저장할 경로를 지정할 수 없도록 하여 서버의 파일을 안전하게 유지하는 데 도움이 됩니다.

메서드를 SaveAs 호출하기 전에 속성을 사용하여 HasFile 컨트롤에 FileUpload 업로드할 파일이 포함되어 있는지 확인해야 합니다. 반환되면 HasFile 메서드를 호출합니다SaveAs.true 반환 false되는 경우 컨트롤에 파일이 포함되어 있지 않음을 나타내는 메시지를 사용자에게 표시합니다. 파일이 있는지 확인하기 위해 오류 처리 코드를 제공하지 않으면 존재하지 않는 파일을 저장하려고 하면 예외가 HttpException throw됩니다.

호출이 SaveAs 작동하려면 ASP.NET 애플리케이션이 서버의 디렉터리에 대한 쓰기 권한이 있어야 합니다. 애플리케이션에서 쓰기 액세스 권한을 얻을 수 있는 두 가지 방법이 있습니다. 업로드된 파일을 저장할 디렉터리에서 애플리케이션이 실행 중인 계정에 대한 쓰기 권한을 명시적으로 부여할 수 있습니다. 또는 ASP.NET 애플리케이션에 부여되는 신뢰 수준을 높일 수 있습니다. 애플리케이션의 실행 디렉터리에 대한 쓰기 액세스를 얻으려면 애플리케이션에 신뢰 수준이 값으로 설정된 AspNetHostingPermissionLevel.Medium 개체를 부여 AspNetHostingPermission 해야 합니다. 신뢰 수준을 높이면 서버의 리소스에 대한 애플리케이션의 액세스가 증가합니다. 애플리케이션을 제어하는 악의적인 사용자도 이 더 높은 신뢰 수준에서 실행할 수 있으므로 이는 안전한 방법이 아닙니다. 애플리케이션을 실행하는 데 필요한 최소 권한이 있는 사용자의 컨텍스트에서 ASP.NET 애플리케이션을 실행하는 것이 가장 좋습니다. ASP.NET 애플리케이션의 보안에 대한 자세한 내용은 웹 애플리케이션 및 ASP.NET 신뢰 수준 및 정책 파일에대한 기본 보안 사례를 참조하세요.

적용 대상

추가 정보