FileUpload.SaveAs(String) メソッド

定義

アップロードしたファイルの内容を Web サーバー上の指定したパスに保存します。

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 、アップロードされたファイルの内容を Web サーバー上の指定されたパスに保存します。

ユーザーが FileUpload アップロードするファイルを選択した後、コントロールによってファイルがサーバーに自動的に保存されることはありません。 ユーザーが指定したファイルを送信できるように、コントロールまたはメカニズムを明示的に指定する必要があります。 たとえば、ユーザーがファイルをアップロードするためにクリックするボタンを指定できます。 指定したファイルを保存するために記述するコードは、 メソッドを SaveAs 呼び出す必要があります。これにより、ファイルの内容がサーバー上の指定したパスに保存されます。 通常、 メソッドは、 SaveAs サーバーへのポストバックを発生させるイベントのイベント処理メソッドで呼び出されます。 たとえば、ファイルを送信するボタンを指定した場合、ファイルをサーバーに保存するコードを、click イベントのイベント処理メソッド内に含めることができました。

メソッドを SaveAs 呼び出すときは、アップロードしたファイルを保存するサーバー上のディレクトリの完全パスを指定する必要があります。 アプリケーション コードでパスを明示的に指定しない場合、 HttpException ユーザーがファイルをアップロードしようとすると例外がスローされます。 この動作は、アップロードするファイルを保存するパスをユーザーが指定できないようにすることで、サーバー上のファイルをセキュリティで保護するのに役立ちます。

メソッドを呼び出す前に SaveAs 、 プロパティを HasFile 使用して、コントロールに FileUpload アップロードするファイルが含まれていることを確認する必要があります。 が HasFile を返す場合は true、 メソッドを SaveAs 呼び出します。 が返された false場合は、コントロールにファイルが含まれていないことを示すメッセージをユーザーに表示します。 ファイルが存在することを確認するエラー処理コードを指定しない場合、存在しないファイルを保存しようとすると例外が HttpException スローされます。

を呼び出して SaveAs 機能させるには、ASP.NET アプリケーションがサーバー上のディレクトリへの書き込みアクセス権を持っている必要があります。 アプリケーションで書き込みアクセスを取得するには、2 つの方法があります。 アップロードされたファイルが保存されるディレクトリ内で、アプリケーションが実行されているアカウントへの書き込みアクセス権を明示的に付与できます。 または、ASP.NET アプリケーションに付与される信頼レベルを上げることができます。 アプリケーションの実行中のディレクトリへの書き込みアクセス権を取得するには、信頼レベルが値に AspNetHostingPermission 設定されたオブジェクトをアプリケーションに AspNetHostingPermissionLevel.Medium 付与する必要があります。 信頼レベルを上げると、サーバー上のリソースへのアプリケーションのアクセスが増加します。 アプリケーションの制御を取得する悪意のあるユーザーも、この高いレベルの信頼の下で実行できるため、これはセキュリティで保護されたアプローチではないことに注意してください。 アプリケーションの実行に必要な最小限の特権を持つユーザーのコンテキストで、ASP.NET アプリケーションを実行することをお勧めします。 ASP.NET アプリケーションのセキュリティの詳細については、「 Web アプリケーションの基本的なセキュリティ プラクティス 」および「 信頼レベルとポリシー ファイルの ASP.NET」を参照してください。

適用対象

こちらもご覧ください