Share via


FileUpload.GetHtml Method

Displays the FileUpload helper on a Web page.

Namespace:  Microsoft.Web.Helpers
Assembly:  Microsoft.Web.Helpers (in Microsoft.Web.Helpers.dll)

Syntax

'Declaration
Public Shared Function GetHtml ( _
    name As String, _
    initialNumberOfFiles As Integer, _
    allowMoreFilesToBeAdded As Boolean, _
    includeFormTag As Boolean, _
    addText As String, _
    uploadText As String _
) As HtmlString
'Usage
Dim name As String
Dim initialNumberOfFiles As Integer
Dim allowMoreFilesToBeAdded As Boolean
Dim includeFormTag As Boolean
Dim addText As String
Dim uploadText As String
Dim returnValue As HtmlString

returnValue = FileUpload.GetHtml(name, _
    initialNumberOfFiles, allowMoreFilesToBeAdded, _
    includeFormTag, addText, uploadText)
public static HtmlString GetHtml(
    string name,
    int initialNumberOfFiles,
    bool allowMoreFilesToBeAdded,
    bool includeFormTag,
    string addText,
    string uploadText
)
public:
static HtmlString^ GetHtml(
    String^ name, 
    int initialNumberOfFiles, 
    bool allowMoreFilesToBeAdded, 
    bool includeFormTag, 
    String^ addText, 
    String^ uploadText
)
public static function GetHtml(
    name : String, 
    initialNumberOfFiles : int, 
    allowMoreFilesToBeAdded : boolean, 
    includeFormTag : boolean, 
    addText : String, 
    uploadText : String
) : HtmlString

Parameters

  • name
    Type: System.String
    (Optional) The value for the name attribute of the HTML input element that is rendered for this helper.
  • initialNumberOfFiles
    Type: System.Int32
    (Optional) The initial number of file upload fields to display. The default is 1. If allowMoreFilesToBeAdded is true, users can add more upload fields.
  • allowMoreFilesToBeAdded
    Type: System.Boolean
    (Optional) true to allow more file upload fields to be added by the user at run time; otherwise, false. The default is true.
  • includeFormTag
    Type: System.Boolean
    (Optional) true to include a form element around all file-upload input elements and the around the submit button; otherwise, false. The default is true.
  • addText
    Type: System.String
    (Optional) The text to display as a link that lets users add file upload fields.
  • uploadText
    Type: System.String
    (Optional) The text to display on the submit button.

Return Value

Type: HtmlString
The HTML markup that is used to render file-upload input elements. If includeFormTag is true, returns the input elements and a submit button inside a form element.

Remarks

If you set the includeFormTag parameter to false, you must make sure that the HTML markup that is rendered by this method is included in a form element and that the page includes a submit button.

Examples

The following example shows how to use the GetHtml method to render HTML markup that lets users upload a single file.

@{  
    var fileName = "";
    if (IsPost) {
        var fileSavePath = "";
        var uploadedFile = Request.Files[0];
        fileName = Path.GetFileName(uploadedFile.FileName);
        fileSavePath = Server.MapPath("/App_Data/UploadedFiles/" + 
          fileName);
        uploadedFile.SaveAs(fileSavePath);
    } 
}
<!DOCTYPE html>
<html>
    <head>
    <title>FileUpload - Single-File Example</title>
    </head>
    <body>
    <h1>FileUpload - Single-File Example</h1>
    @FileUpload.GetHtml(
        name: "",
        initialNumberOfFiles: 1, 
        allowMoreFilesToBeAdded: true, 
        includeFormTag: true, 
        addText: "More Files",
        uploadText: "Upload")
    @if (IsPost) {
        <span>File uploaded!</span><br/>
    }   
    </body>
</html>

In the example, the parameters that the helper will render a single field to specify the file to upload and that the submit button that will is labeled "Upload".

When the Upload button is clicked, the code at the top of the page gets the file and saves it. When files are uploaded, the Request object that is used to get values from form fields has a Files array that contains the file or files that have been uploaded. For example, to get the first uploaded file, use Request.Files[0], to get the second file, use Request.Files[1], and so on.

Use a variable when fetching an uploaded file. The example shows a variable named uploadedFile. To determine the name of the uploaded file, use the FileName property of the uploadedFile. However, FileName contains the name of the file as represented on the client computer, which includes the entire path. It might look like this:

C:\Users\Public\Sample.txt

This is almost never the path that you want to use on the server to save the uploaded file. To remove the path information from the file name, use the Path.GetFileName method, as in the following example:

Path.GetFileName(uploadedFile.FileName)

The Path object is a utility that has a number of methods that can be used to strip paths, combine paths, and so on.

After you have determined the name of the uploaded file, you can build a new path to store the uploaded file on the Web site. By combining Server.MapPath, the folder names (App_Data/UploadedFiles), and the newly stripped file name, the new path can be created. Call the uploaded file's SaveAs method to save the file.

The FileUpload class can be used to upload more than one file at a time. The following example shows how to use the GetHtml method to upload multiple files.

@{
  var message = "";
  if (IsPost) {
      var fileName = "";
      var fileSavePath = "";
      int numFiles = Request.Files.Count;
      int uploadedCount = 0;
      for(int i =0; i < numFiles; i++) {
          var uploadedFile = Request.Files[i];
          if (uploadedFile.ContentLength > 0) {
              fileName = Path.GetFileName(uploadedFile.FileName); 
              fileSavePath = Server.MapPath("/App_Data/UploadedFiles/" + 
                fileName);
              uploadedFile.SaveAs(fileSavePath);
              uploadedCount++;
          }
       }
       message = "File upload complete. Total files uploaded: " + 
         uploadedCount.ToString();
   }
}
<!DOCTYPE html>
<html>
    <head><title>FileUpload - Multiple File Example</title></head>
<body>
    <form id="myForm" method="post"
       enctype="multipart/form-data"
       action="">
    <div>
    <h1>File Upload - Multiple-File Example</h1>
    @if (!IsPost) {
        @FileUpload.GetHtml(
            initialNumberOfFiles: 2, 
            allowMoreFilesToBeAdded: true, 
            includeFormTag: true, 
            addText: "Add another file", 
            uploadText: "Upload")
        }
    <span>@message</span>
    </div>
    </form>
</body>
</html>

In the example, the FileUpload class in the body of the page is configured to allow users upload two files by default. Because allowMoreFilesToBeAdded is set to true, the helper renders a link that allows user add more upload boxes.

To process the files that the user uploads, the code get a file from Request.Files and then saves it. To determine how many files the user is uploading, use the Request.Files.Count value. You can then loop through Request.Files, fetch each file in turn, and save it.

The variable i is just a temporary counter that will go from zero to whatever upper limit is set. In this case, the upper limit is the number of files. But because the counter starts at zero, as is typical for counting scenarios in ASP.NET, the upper limit is actually one less than the file count. (If three files are uploaded, the count is zero to 2.)

The uploadedCount variable totals all the files that are successfully uploaded and saved. This code accounts for the possibility that an expected file may not be able to be uploaded.

Permissions

  • Medium trust for the immediate caller. This member can be used by partially trusted code.

See Also

Reference

FileUpload Class

Microsoft.Web.Helpers Namespace

Other Resources

ASP.NET Web Pages with Razor Syntax