FileUpload クラスとは? わかりやすく解説

FileUpload クラス

メモ : このクラスは、.NET Framework version 2.0新しく追加されたものです。

ユーザーファイル選択してサーバーアップロードするためのテキスト ボックス コントロール参照ボタン表示します

名前空間: System.Web.UI.WebControls
アセンブリ: 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
/** @attribute ControlValuePropertyAttribute("FileBytes") */ 
/** @attribute ValidationPropertyAttribute("FileName") */ 
public class FileUpload extends WebControl
ControlValuePropertyAttribute("FileBytes") 
ValidationPropertyAttribute("FileName") 
public class FileUpload extends
 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 設定スキーマ) に関するトピック参照してください

大きファイルアップロードする場合次のエラー メッセージ表示されることがあります

このエラー メッセージ表示されたら、アプリケーションの Web.config ファイルの processModel 要素memoryLimit 属性の値を大きくます。memoryLimit 属性は、ワーカー プロセス使用できる最大メモリ量を示しますワーカー プロセス使用するメモリ量が memoryLimit の量を超えると、新しプロセス作成され、そのプロセス置換されます。現在のすべての要求は、新しプロセス再度割り当てられます。

要求の処理中にアップロードするファイルメモリ内とサーバー上のどちらに一時的に格納するかを制御するには、httpRuntime 要素requestLengthDiskThreshold 属性設定します。この属性設定すると、入力ストリーム バッファサイズ管理できます既定値256 バイトです。この値は、maxRequestLength 属性指定する値を超えないように指定してください

使用例使用例

このセクションには、4 つコード例含まれています。

注意に関するメモ注意

これらのコード例では 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>
.NET Framework のセキュリティ.NET Frameworkセキュリティ
継承階層継承階層
System.Object
   System.Web.UI.Control
     System.Web.UI.WebControls.WebControl
      System.Web.UI.WebControls.FileUpload
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
FileUpload メンバ
System.Web.UI.WebControls 名前空間
SaveAs


このページでは「.NET Framework クラス ライブラリ リファレンス」からFileUpload クラスを検索した結果を表示しています。
Weblioに収録されているすべての辞書からFileUpload クラスを検索する場合は、下記のリンクをクリックしてください。
 全ての辞書からFileUpload クラスを検索

英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「FileUpload クラス」の関連用語

FileUpload クラスのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



FileUpload クラスのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2024 Microsoft.All rights reserved.

©2024 GRAS Group, Inc.RSS