FileUpload イベント

名前 | 説明 | |
---|---|---|
![]() | DataBinding | サーバー コントロールがデータ ソースに連結すると発生します。 ( Control から継承されます。) |
![]() | Disposed | サーバー コントロールがメモリから解放されると発生します。これは、ASP.NET ページが要求されている場合のサーバー コントロールの有効期間における最終段階です。 ( Control から継承されます。) |
![]() | Init | サーバー コントロールが初期化されると発生します。これは、サーバー コントロールの有効期間における最初の手順です。 ( Control から継承されます。) |
![]() | Load | サーバー コントロールが Page オブジェクトに読み込まれると発生します。 ( Control から継承されます。) |
![]() | PreRender | Control オブジェクトの読み込み後、表示を開始する前に発生します。 ( Control から継承されます。) |
![]() | Unload | サーバー コントロールがメモリからアンロードされると発生します。 ( Control から継承されます。) |

FileUpload クラス
アセンブリ: System.Web (system.web.dll 内)

<ControlValuePropertyAttribute("FileBytes")> _ <ValidationPropertyAttribute("FileName")> _ Public Class FileUpload Inherits WebControl
[ControlValuePropertyAttribute("FileBytes")] [ValidationPropertyAttribute("FileName")] public class FileUpload : WebControl
[ControlValuePropertyAttribute(L"FileBytes")] [ValidationPropertyAttribute(L"FileName")] public ref class FileUpload : public WebControl

FileUpload クラスは、ユーザーがクライアントでファイルを選択してそのファイルを Web サーバーにアップロードするためのテキスト ボックス コントロールと参照ボタンを表示します。ユーザーは、コントロールのテキスト ボックスにローカル コンピュータのファイルへの完全パス (C:\MyFiles\TestFile.txt など) を入力することによって、アップロードするファイルを指定します。[参照] ボタンをクリックし、[ファイルの選択] ダイアログ ボックスでそのファイルを検索して選択することもできます。
FileUpload コントロールは、アップロードするファイルをユーザーが選択した後はファイルをサーバーに自動的に保存しません。指定したファイルをユーザーが送信できるようにするコントロールまたはメカニズムを明示的に指定する必要があります。たとえば、ユーザーがクリックするとファイルがアップロードされるようなボタンを指定します。指定したファイルを保存するために記述したコードでは、サーバー上の指定したパスにファイルの内容を保存する SaveAs メソッドを呼び出す必要があります。通常、SaveAs メソッドは、サーバーへのポストバックを発生させるイベントの、イベント処理メソッドで呼び出されます。たとえば、ファイルを送信するボタンを指定した場合、ファイルを保存するコードはクリック イベントのイベント処理メソッド内に配置します。
SaveAs メソッドを呼び出してファイルをサーバーに保存する前に、HasFile プロパティを使用して、FileUpload コントロールにファイルが格納されていることを確認します。HasFile によって true が返される場合、SaveAs メソッドを呼び出します。false が返される場合、コントロールにファイルが格納されていないことを示すメッセージがユーザーに表示されます。PostedFile プロパティには既定で 0 バイトが格納されるため、このプロパティを調べることによってアップロードするファイルが存在するかどうかを確認しないでください。このプロパティで確認すると、FileUpload コントロールが空の場合でも PostedFile プロパティから null 以外の値が返されます。
SaveAs メソッドを呼び出す場合は、アップロードしたファイルの保存先となるディレクトリへの完全パスを指定する必要があります。アプリケーション コードにパスを明示的に指定しない場合は、ユーザーがファイルをアップロードしようとすると、例外がスローされます。この動作によって、ユーザーによるアプリケーションのディレクトリ構造の任意の場所への書き込みおよび機密性の高いルート ディレクトリへのアクセスが防止され、サーバー上のファイルを安全に保持できます。
SaveAs メソッドは、アップロードされたファイルを指定したディレクトリに書き込みます。そのため、ASP.NET アプリケーションにサーバー上のディレクトリに対する書き込みアクセスが必要です。アプリケーションが書き込みアクセスを取得するには、2 つの方法があります。アプリケーションを実行中のアカウントに対しては、アップロードされたファイルの保存先となるディレクトリでの書き込みアクセスを明示的に許可できます。または、ASP.NET アプリケーションに与えている信頼レベルを上げることもできます。アプリケーションの実行ディレクトリへの書き込みアクセスを取得するには、信頼レベルが AspNetHostingPermissionLevel.Medium 値に設定された AspNetHostingPermission オブジェクトがアプリケーションに許可されている必要があります。信頼レベルを上げると、アプリケーションからサーバー上のリソースへのアクセス権限が拡大します。ただし、アプリケーションの制御を取得した悪意のあるユーザーもこの高い信頼レベルでアプリケーションを実行できるので、この方法は安全ではありません。アプリケーションの実行に必要な最小限の特権を持つユーザーのコンテキストで ASP.NET アプリケーションを実行することをお勧めします。ASP.NET アプリケーションのセキュリティの詳細については、「Web アプリケーションのセキュリティに関する基本的な対策」と「ASP.NET 信頼レベルとポリシー ファイル」を参照してください。
FileUpload コントロールを使用してアップロードするクライアント上のファイル名を取得するには、FileName プロパティを使用します。このプロパティが返すファイル名には、クライアント上のファイルへのパスが含まれません。
FileContent プロパティは、アップロードするファイルを指す Stream オブジェクトを取得します。このプロパティを使用して、ファイルの内容にバイトとしてアクセスします。たとえば、FileContent プロパティによって返される Stream オブジェクトを使用してファイルの内容をバイトとして読み取り、その内容をバイト配列に格納します。または、FileBytes プロパティを使用して、ファイル内のすべてのバイトを取得することもできます。
PostedFile プロパティは、アップロードするファイルの基になる HttpPostedFile オブジェクトを取得します。このプロパティを使用すると、ファイルのその他のプロパティにアクセスできます。ContentLength プロパティは、ファイルの長さを取得します。ContentType プロパティは、ファイルの MIME コンテンツ タイプを取得します。また、PostedFile プロパティを使用して、FileName プロパティ、InputStream プロパティ、および SaveAs メソッドにアクセスできます。ただし、FileName プロパティ、FileContent プロパティ、および SaveAs メソッドにも同じ機能があります。
サービス拒否攻撃を防ぐ方法の 1 つとして、FileUpload コントロールを使用してアップロードできるファイルのサイズを制限する方法があります。アップロードするファイルの種類に適したサイズ制限を設定する必要があります。既定のサイズ制限は 4096 KB (4 MB) です。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 ファイルの processModel 要素の memoryLimit 属性の値を大きくします。memoryLimit 属性は、ワーカー プロセスが使用できる最大メモリ量を示します。ワーカー プロセスが使用するメモリ量が memoryLimit の量を超えると、新しいプロセスが作成され、そのプロセスと置換されます。現在のすべての要求は、新しいプロセスに再度割り当てられます。
要求の処理中にアップロードするファイルをメモリ内とサーバー上のどちらに一時的に格納するかを制御するには、httpRuntime 要素の requestLengthDiskThreshold 属性を設定します。この属性を設定すると、入力ストリーム バッファのサイズを管理できます。既定値は 256 バイトです。この値は、maxRequestLength 属性に指定する値を超えないように指定してください。

-
最初のコード例では、コードで指定したパスにファイルを保存する FileUpload コントロールを作成する方法を示します。
-
2 つ目のコード例では、アプリケーションのファイル システム内の指定したディレクトリにファイルを保存する FileUpload コントロールを作成する方法を示します。
-
3 つ目のコード例では、指定したパスにファイルを保存し、アップロードできるファイルのサイズを制限する FileUpload コントロールを作成する方法を示します。
-
4 つ目のコード例では、指定したパスにファイルを保存し、拡張子が .doc または .xls のファイルのアップロードだけを許可する FileUpload コントロールを作成する方法を示します。
![]() |
---|
これらのコード例では FileUpload コントロールの基本的な構文を説明します。ただし、ファイルを保存する前に終了しておく必要がある必須のエラー チェックの一部については説明しません。すべての例については、「SaveAs」を参照してください。 |
コードで指定したパスにファイルを保存する FileUpload コントロールを作成する方法を次のコード例に示します。サーバー上の指定したパスにファイルを保存するには、SaveAs メソッドを呼び出します。
<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Sub UploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) ' Specify the path on the server to ' save the uploaded file to. Dim savePath As String = "c:\temp\uploads\" ' Before attempting to perform operations ' on the file, verify that the FileUpload ' control contains a file. If (FileUpload1.HasFile) Then ' Get the name of the file to upload. Dim fileName As String = 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 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." End If End Sub </script> <html > <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) { // 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 > <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>
アプリケーションのファイル システム内の指定したディレクトリにファイルを保存する FileUpload コントロールを作成する方法を次のコード例に示します。現在実行しているサーバー アプリケーションのルート ディレクトリの物理ファイル システム パスを取得するには、HttpRequest.PhysicalApplicationPath プロパティを使用します。サーバー上の指定したパスにファイルを保存するには、SaveAs メソッドを呼び出します。
<%@ Page Language="VB" %> <html> <head> <script runat="server"> Sub UploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) ' 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". Dim saveDir As String = "\Uploads\" ' Get the physical file system path for the currently ' executing application. Dim appPath As String = Request.PhysicalApplicationPath ' Before attempting to save the file, verify ' that the FileUpload control contains a file. If (FileUpload1.HasFile) Then Dim savePath As String = appPath + saveDir + 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." End If End Sub </script> </head> <body> <h3>FileUpload Class Example: Save To Application Directory</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>
コードで指定したパスにファイルを保存する FileUpload コントロールを作成する方法を次のコード例に示します。このコントロールは、アップロードできるファイルのサイズを 5 MB に制限します。基になる ContentLength プロパティにアクセスしてファイル サイズを返すには、PostedFile プロパティを使用します。アップロードするファイルのサイズが 5 MB 未満の場合、SaveAs メソッドを呼び出して、サーバー上の指定したパスにファイルを保存します。アプリケーション コードで最大ファイル サイズ設定を確認するだけでなく、アプリケーションの構成ファイルで httpRuntime 要素の maxRequestLength 属性を最大許容サイズに設定できます。
<%@ Page Language="VB" %> <html> <head> <script runat="server"> Sub UploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) ' Specify the path on the server to ' save the uploaded file to. Dim savePath As String = "c:\temp\uploads\" ' Before attempting to save the file, verify ' that the FileUpload control contains a file. If (FileUpload1.HasFile) Then ' Get the size in bytes of the file to upload. Dim fileSize As Integer = FileUpload1.PostedFile.ContentLength ' Allow only files less than 5,100,000 bytes (approximately 5 MB) to be uploaded. If (fileSize < 5100000) Then ' Append the name of the uploaded file to the path. savePath += 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 5 MB size limit." End If Else ' Notify the user that a file was not uploaded. UploadStatusLabel.Text = "You did not specify a file to upload." End If End Sub </script> </head> <body> <h3>FileUpload Class Example: Check File Size</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>
コードで指定したパスにファイルを保存する FileUpload コントロールを作成する方法を次のコード例に示します。この例では、拡張子が .doc または .xls のファイルだけをアップロードできます。アップロードするファイルの拡張子を返すには、Path.GetExtension メソッドを呼び出します。ファイルの拡張子が .doc または .xls の場合、SaveAs メソッドを呼び出して、サーバー上の指定したパスにファイルを保存します。
<%@ Page Language="VB" %> <html> <head> <script runat="server"> Sub UploadBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) ' Specify the path on the server to ' save the uploaded file to. Dim savePath As String = "c:\temp\uploads\" ' Before attempting to save the file, verify ' that the FileUpload control contains a file. If (FileUpload1.HasFile) Then ' Get the name of the file to upload. Dim fileName As String = FileUpload1.FileName ' Get the extension of the uploaded file. Dim extension As String = System.IO.Path.GetExtension(fileName) ' Allow only files with .doc or .xls extensions ' to be uploaded. If (extension = ".doc") Or (extension = ".xls") Then ' 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." End If Else ' Notify the user that a file was not uploaded. UploadStatusLabel.Text = "You did not specify a file to upload." End If End Sub </script> </head> <body> <h3>FileUpload Class Example: Check File Extension</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="UploadBtn" Text="Upload file" OnClick="UploadBtn_Click" runat="server"> </asp:Button> <hr /> <asp:Label id="UploadStatusLabel" runat="server"> </asp:Label> </form> </body> </html>


System.Web.UI.Control
System.Web.UI.WebControls.WebControl
System.Web.UI.WebControls.FileUpload


Windows 98, Windows 2000 SP4, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


FileUpload コンストラクタ
アセンブリ: System.Web (system.web.dll 内)


FileUpload コンストラクタを使用して、FileUpload クラスの新しいインスタンスを初期化します。FileUpload コントロールは、アップロードするファイルをユーザーが選択した後はファイルをサーバーに自動的に保存しません。指定したファイルをユーザーが送信できるようにするコントロールまたはメカニズムを明示的に指定する必要があります。たとえば、ユーザーがクリックするとファイルがアップロードされるようなボタンを指定します。

FileUpload クラスの新しいインスタンスを初期化する方法を次のコード例に示します。この例では、コンストラクタの構文を説明していますが、コントロールの作成後にそのコントロールには機能を追加しません。
このコード例は、FileUpload クラスのトピックで取り上げているコード例の一部分です。
<%@ Page Language="VB" %> <html> <head> <script runat="server"> Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) ' Create a FileUpload control. Dim FileUpload1 As New FileUpload ' Add the FileUpload control to the Controls collection ' of the PlaceHolder control. PlaceHolder1.Controls.Add(FileUpload1) End Sub </script> </head> <body> <h3>FileUpload Constructor Example</h3> <form ID="Form1" runat="server"> <asp:PlaceHolder id="PlaceHolder1" runat="server"> </asp:PlaceHolder> <hr> <asp:Button id="Button1" Text="Create and show a FileUpload control" OnClick="Button1_Click" runat="server"/> </form> </body> </html>

Windows 98, Windows 2000 SP4, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


FileUpload プロパティ



FileUpload メソッド



FileUpload メンバ
ユーザーがファイルを選択してサーバーにアップロードするためのテキスト ボックス コントロールと参照ボタンを表示します。
FileUpload データ型で公開されるメンバを以下の表に示します。






名前 | 説明 | |
---|---|---|
![]() | DataBinding | サーバー コントロールがデータ ソースに連結すると発生します。(Control から継承されます。) |
![]() | Disposed | サーバー コントロールがメモリから解放されると発生します。これは、ASP.NET ページが要求されている場合のサーバー コントロールの有効期間における最終段階です。(Control から継承されます。) |
![]() | Init | サーバー コントロールが初期化されると発生します。これは、サーバー コントロールの有効期間における最初の手順です。(Control から継承されます。) |
![]() | Load | サーバー コントロールが Page オブジェクトに読み込まれると発生します。(Control から継承されます。) |
![]() | PreRender | Control オブジェクトの読み込み後、表示を開始する前に発生します。(Control から継承されます。) |
![]() | Unload | サーバー コントロールがメモリからアンロードされると発生します。(Control から継承されます。) |

- FileUploadのページへのリンク