共用方式為


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 當使用者嘗試上傳檔案時會拋出例外。 這種行為有助於保護伺服器上的檔案,因為使用者無法指定儲存檔案的路徑。

在呼叫方法 SaveAs 之前,你應該先用這個 HasFile 屬性來確認 FileUpload 控制項是否包含要上傳的檔案。 如果回傳trueHasFile就呼叫該SaveAs方法。 如果回傳 false,則顯示訊息給使用者,表示控制項內不包含檔案。 如果你沒有提供錯誤處理程式碼來驗證檔案的存在,嘗試儲存不存在的檔案會拋 HttpException 出異常。

要呼叫 , SaveAs ASP.NET 應用程式必須擁有對伺服器目錄的寫入權限。 應用程式有兩種方式可以取得寫入權限。 你可以明確授權該應用程式執行的帳號,在上傳檔案儲存的目錄中寫入權限。 或者,你也可以提高對 ASP.NET 申請的信任程度。 要取得應用程式執行目錄的寫入權限,應用程式必須獲得 AspNetHostingPermission 該物件,且信任等級設定為該 AspNetHostingPermissionLevel.Medium 值。 提升信任度,應用程式對伺服器資源的存取權也會增加。 請注意,這並非安全方法,因為惡意使用者若控制你的應用程式,也能在此較高信任層級下執行。 最佳實務是在擁有最低權限的使用者情境下執行 ASP.NET 應用程式。 欲了解更多關於 ASP.NET 應用安全資訊,請參閱 網頁應用基本安全實務ASP.NET 信任等級與政策檔案

適用於

另請參閱