Freigeben über


How to: Upload Files with the FileUpload Web Server Control

The FileUpload Web server control allows you to provide users with a way to send a file from their computer to the server. The file to be uploaded is submitted to the server as part of the browser request during postback. After the file has completed uploading, you can manage the file in your code.

NoteNote

The maximum size file that can be uploaded depends on the value of the MaxRequestLength configuration setting. If users attempt to upload a file that is longer than the maximum, the upload fails.

To upload a file with the FileUpload Web server control

  1. Add a FileUpload control to the page.

    NoteNote

    For security reasons, you cannot pre-load the name of a file into the FileUpload control.

  2. In a handler for an event, such as the page's Load event, do the following:

    1. Check that the FileUpload control has an uploaded file by testing its HasFile property.

    2. Check the file name or MIME type of the file to make sure that users have uploaded a file that you want to accept. To check the MIME type, get the HttpPostedFile object exposed as the FileUpload control's PostedFile property. You can then get the MIME type by checking the posted file's ContentType property.

      Security noteSecurity Note

      MIME types for uploaded files can be spoofed under some circumstances, so checking the file's MIME type alone is not a reliable security check.

    3. Save the file to a location you specify. You can call the SaveAs method of the HttpPostedFile object. Alternatively, you can manage the uploaded file as a byte array or stream using the HttpPostedFile object's InputStream property.

    The following example shows how to work with an uploaded file. The code checks the file name extension of the uploaded file against a hard-coded list of allowed file name extensions and rejects all other types of files. The file is then written to an UploadedImages folder in the current Web site. The uploaded file is saved with the same file name that it had on the client computer. The FileName property of the FileUpload control is used because the FileName property of the HttpPostedFile object returns the complete path of the file on the client computer.

    Security noteSecurity Note

    Do not display the path and name of the saved file to users; doing so can reveal information that might be useful to malicious users.

    Protected Sub Page_Load(ByVal sender As Object, 
            ByVal e As System.EventArgs) Handles Me.Load
        If IsPostBack Then
            Dim path As String = Server.MapPath("~/UploadedImages/")
            Dim fileOK As Boolean = False
            If FileUpload1.HasFile Then
                Dim fileExtension As String
                fileExtension = System.IO.Path. _
                    GetExtension(FileUpload1.FileName).ToLower()
                Dim allowedExtensions As String() = _
                    {".jpg", ".jpeg", ".png", ".gif"}
                For i As Integer = 0 To allowedExtensions.Length - 1
                    If fileExtension = allowedExtensions(i) Then
                       fileOK = True
                    End If
                Next
                If fileOK Then
                    Try
                        FileUpload1.PostedFile.SaveAs(path & _
                             FileUpload1.FileName)
                        Label1.Text = "File uploaded!"
                    Catch ex As Exception
                        Label1.Text = "File could not be uploaded."
                    End Try
                Else
                    Label1.Text = "Cannot accept files of this type."
                End If
            End If
        End If
    End Sub
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if(IsPostBack)
        {
            Boolean fileOK = false;
            String path = Server.MapPath("~/UploadedImages/");
            if (FileUpload1.HasFile) 
            {
                String fileExtension = 
                    System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
                String[] allowedExtensions = 
                    {".gif", ".png", ".jpeg", ".jpg"};
              for (int i = 0; i < allowedExtensions.Length; i++)
              {
                   if (fileExtension == allowedExtensions[i])
                   {
                        fileOK = true;
                   }
              }
            }
    
            if (fileOK)
            {
                try
                {
                    FileUpload1.PostedFile.SaveAs(path 
                        + FileUpload1.FileName);
                    Label1.Text = "File uploaded!";
                }
                catch (Exception ex)
                {
                    Label1.Text = "File could not be uploaded.";
                }
            }
            else
            {
                Label1.Text = "Cannot accept files of this type.";
            }
        }
    }
    

See Also

Concepts

FileUpload Web Server Control Overview