Uploading Files Using the File Field Control

Embed Size (px)

Citation preview

  • 7/28/2019 Uploading Files Using the File Field Control

    1/16

    6/20/13 Uploading Files Using the File Field Control

    msdn.microsoft.com/en-us/library/aa478971.aspx 1/16

    Uploading Files Usingthe File Field Control75 out of 104 rated this helpful

    By Bill Evjen

    Reuters

    Feburary 2004

    Applies to:

    Microsoft ASP.NET

    Summary: Learn how to use the Microsoft ASP.NET File

    Field control to allow your end-users to upload one ormore files to your server. (16 printed pages)

    Contents

    Introduction

    Looking Closely at the File Field Control

    Working Around File Size Limitations

    Controlling Uploaded File Types

    Uploading Multiple Files at the Same Time

    Conclusion

    Related Books

    IntroductionMicrosoft ASP.NET Web Forms are all about

    communicating with an end-user to abstract what

    information you need to from them depending on the

    service administered. In many cases with Web Forms, it is

    usually simply textual data that is collected and stored.

    However, there are many cases where you are going to

    need more than simple textual data; you may want your

    users to upload files to the server.

    For instance, your application can have a document library

    that is shared with all users. There are plenty of examples,

    but invariably you will need this ability to upload any type

    of document for storage, or to have your application take

    action upon the document once it is uploaded.

    In any case, ASP.NET provides you with a simple ability to

    upload documents to the server with just a little work on

    your part. This article describes how to use the File Fieldcontrol for uploading documents to your Web server.

    Looking Closely at the File Field

    http://msdn.microsoft.com/en-us/library/aa478971.aspx#aspnet-fileupload_topic4http://msdn.microsoft.com/en-us/library/aa478971.aspx#aspnet-fileupload_topic2chttp://msdn.microsoft.com/en-us/library/aa478971.aspx#aspnet-fileupload_topic2bhttp://msdn.microsoft.com/en-us/library/aa478971.aspx#aspnet-fileupload_topic2bhttp://msdn.microsoft.com/en-us/library/aa478971.aspx#aspnet-fileupload_topic2ahttp://msdn.microsoft.com/en-us/library/aa478971.aspx#aspnet-fileupload_topic2ahttp://msdn.microsoft.com/en-us/library/aa478971.aspx#aspnet-fileupload_topic2http://msdn.microsoft.com/en-us/library/aa478971.aspx#aspnet-fileupload_topic2http://msdn.microsoft.com/en-us/library/aa478971.aspx#aspnet-fileupload_topic4http://msdn.microsoft.com/en-us/library/aa478971.aspx#aspnet-fileupload_topic3http://msdn.microsoft.com/en-us/library/aa478971.aspx#aspnet-fileupload_topic2chttp://msdn.microsoft.com/en-us/library/aa478971.aspx#aspnet-fileupload_topic2bhttp://msdn.microsoft.com/en-us/library/aa478971.aspx#aspnet-fileupload_topic2ahttp://msdn.microsoft.com/en-us/library/aa478971.aspx#aspnet-fileupload_topic2http://msdn.microsoft.com/en-us/library/aa478971.aspx#aspnet-fileupload_topic1
  • 7/28/2019 Uploading Files Using the File Field Control

    2/16

    6/20/13 Uploading Files Using the File Field Control

    msdn.microsoft.com/en-us/library/aa478971.aspx 2/16

    The File Field control uses the HtmlInputFile class and

    is a cool control simply because it does things that were

    difficult to do before ASP.NET (that is, without buying a

    third-party component to do it for you). The File Field

    control uploads files to the server from the client's machine.

    It is important to note that this control is called the File

    Field control in all versions of Microsoft Visual Studio

    .NET, while in the ASP.NET Web Matrix, this control is called

    the FileUpload control. In both cases, you will find the

    control in the HTML section of the Toolbox.

    The File Field control allows access to program the HTML

    tag. This tag is used to work with

    file data within an HTML form. In the past when using

    classic ASP (ASP 3.0 or earlier), many programmers worked

    with third-party components to upload files from the client

    to the server. Now, with .NET and this new control,uploading is taken care of for youand it couldn't be

    simpler. Listing 1 shows you how to use the File Field

    control to upload files to the server.

    Note The sample code is provided in both

    Microsoft Visual Basic (VB) and C#.

    Listing 1. Uploading files to the server using the File

    Field control

    VB

    Sub SubmitButton_Click(Source As Object, e As

    EventArgs)

    If Not (File1.PostedFile Is Nothing) Then

    Try

    File1.PostedFile.SaveAs("C:\Uploads\

    uploadedfile.txt")Span1.InnerHtml = "Upload Successful

    !"

    Catch ex As Exception

    Span1.InnerHtml = "Error saving file

    C:\\" & _

    File1.Value & "
    " & ex.ToS

    tring()

    End Try

    End If

    End Sub

  • 7/28/2019 Uploading Files Using the File Field Control

    3/16

    6/20/13 Uploading Files Using the File Field Control

    msdn.microsoft.com/en-us/library/aa478971.aspx 3/16

    < o y>

    Select a file to upload:

    C#

    void SubmitButton_Click(Object sender, EventA

    rgs e) {

    if (File1.PostedFile != null) {

    try {

    File1.PostedFile.SaveAs("C:\\Uploads

    \\uploadedfile.txt");

    Span1.InnerHtml = "Upload Successful

    !";

    }catch (Exception ex) {

    Span1.InnerHtml = "Error saving file

    C:\\" +

    File1.Value + "
    " + ex.ToS

    tring();

    }

    }

    }

    Select a file to upload:

  • 7/28/2019 Uploading Files Using the File Field Control

    4/16

    6/20/13 Uploading Files Using the File Field Control

    msdn.microsoft.com/en-us/library/aa478971.aspx 4/16

    When the page from Listing 1 is run, you can select a file

    and upload it to the server by clicking the Upload File

    button on the page. This is a great feature that ASP 3.0

    programmers always wished for. Now it is here in .NET!

    With only a few lines of code, it is easy to upload any type

    of files to the server.

    There are some important items we should go over for this

    example so you understand all the needed pieces to make

    this work. First, for the example in Listing 1 to work, you

    have to make the destination folder on the server writeable

    for the account used by ASP.NET so the file can be saved to

    the specified folder.

    If you think your ASP.NET account is not enabled to write to

    the folder you want, simply open up Microsoft WindowsExplorer and navigate to the folder to which you want to

    add this permission. Right-click on the folder (in this case,

    the Uploads folder), and then select Properties. In the

    Properties dialog box, click on the Security tab and make

    sure the ASP.NET Machine Account is included in the list

    and has the proper permissions to write to disk (see Figure

    1).

    Figure 1. Looking at the Security tab of the Uploads

  • 7/28/2019 Uploading Files Using the File Field Control

    5/16

    6/20/13 Uploading Files Using the File Field Control

    msdn.microsoft.com/en-us/library/aa478971.aspx 5/16

    If you don't see the ASP.NET Machine Account under the

    Security tab, you can add it by clicking the Add button and

    entering ASPNET (without the period) in the text area, as

    illustrated in Figure 2.

    Figure 2. Adding the ASP.NET Machine Account to the

    folder security definition

    Click OK to add the ASP.NET Machine Account to the list.

    From here, make sure you give this account the proper

    permissions; then click OK and you are ready to go.

    Looking at the code from Listing 1, you might notice some

    really important things right away. First, the tag

    has been altered by the addition of another attribute. Toupload files to a server, your tag must have the

    attribute enctype="multipart/form-data". Without

    this attribute, the Web form cannot upload the file.

    The Submit button on the page causes an

    OnServerClick event to occur. This event uploads the

    file and then displays a message telling you if the upload

    was successful. If it was unsuccessful, the page displays an

    error message describing why the upload failed.

    By using the tag, the browser

    automatically places a Browse button next to the text field

    on the ASP.NET page. You don't have to program anything

    else for this to occur. When the end user clicks the Browse

    button, he can navigate through the local file system to find

    the file to be uploaded to the server. This is shown in

    Figure 3. Clicking Open will place that filename and the file's

    path within the text field.

  • 7/28/2019 Uploading Files Using the File Field Control

    6/16

    6/20/13 Uploading Files Using the File Field Control

    msdn.microsoft.com/en-us/library/aa478971.aspx 6/16

    Figure 3. Choosing a file

    Working Around File Size Limitations

    You may not realize it, but there is a limit to the size of a

    file that can be uploaded using this technique. By default,

    the maximum size of a file to be uploaded to the server

    using the File Field control is around 4MB. You cannot

    upload anything that is larger than this limit.

    One of the great things about .NET, however, is that it

    usually provides a way around limitations. You can usually

    change the default settings that are in place. To change this

    size limit, you make some changes in either the

    machine.config or web.config file.

    In the machine.config file, find a node called

    that looks like the following:

    A lot is going on in this single node, but the setting that

    takes care of the size of the files to be uploaded is the

    maxRequestLength attribute. By default, this is set to

    4096 kilobytes (KB). Simply change this value to increase the

    size of the files that you can upload to the server. If you

    want to allow 10 megabyte (MB) files to be uploaded to the

    server, set the maxRequestLength value to 11264,

    meaning that the application allows files that are up to

    11000 KB to be uploaded to the server.

    Making this change in the machine.config file applies

    this setting to all the applications that are on the server. Ifyou want to apply this to only the application you are

    working with, then apply this node to the web.config file

    of your application, overriding any setting that is in the

    machine.config file. Make sure this node res ides

  • 7/28/2019 Uploading Files Using the File Field Control

    7/16

    6/20/13 Uploading Files Using the File Field Control

    msdn.microsoft.com/en-us/library/aa478971.aspx 7/16

    between the nodes in the configuration

    file.

    Another setting involved in the size limitation of files to be

    uploaded is the value given to the executionTimeout

    attribute in the node.

    The value given the executionTimeout attribute is the

    number of seconds the upload is allowed to occur beforebeing shut down by ASP.NET. If you are going to allow

    large files to be uploaded to the server, you are also going

    to want to increase this value along with the

    maxRequestLength value.

    One negative with increasing the size of a file that can be

    uploaded is that there are hackers out there who attack

    servers by throwing a large number of requests at them. To

    guard against this, you can actually decrease the size of the

    files that are allowed to be uploaded; otherwise, you may

    find hundreds or even thousands of 10 MB requests hitting

    your server.

    Controlling Uploaded File Types

    There are a several methods you can use to control the

    types of files that are uploaded to the server. Unfortunately,

    there is no bullet-proof method to protect you from

    someone uploading files that would be considered

    malicious. You can take a few steps, however, to make this

    process of allowing end users to upload files a little moremanageable.

    One nice method you can employ is to use the ASP.NET

    validation controls that are provided for free with ASP.NET.

    These controls enable you to do a regular-expression

    check upon the file that is being uploaded to see if the

    extension of the file is one you permit to be uploaded.

    This is ideal for browsers that allow client-side use of the

    validation controls because it forces the checking to be

    done on the client; the file is not uploaded to the server ifthe signature isn't one you allow. Listing 2 shows you an

    example of using validation controls to accomplish this

    task.

    Note The use of validation controls is not

    explained here. Take a look at Validating

    ASP.NET Server Controls for a complete

    explanation of validation controls and how to

    use them in your ASP.NET pages.

    Listing 2: Using validation controls to restrict the types

    of files uploaded to the server

    VB

    http://msdn.microsoft.com/en-us/library/aa479013.aspx
  • 7/28/2019 Uploading Files Using the File Field Control

    8/16

    6/20/13 Uploading Files Using the File Field Control

    msdn.microsoft.com/en-us/library/aa478971.aspx 8/16

    Sub SubmitButton_Click(Source As Object, e As

    EventArgs)

    If Not (File1.PostedFile Is Nothing) Then

    Try

    File1.PostedFile.SaveAs("C:\Uploads\

    uploadedfile.txt")

    Span1.InnerHtml = "Upload Successful

    !"

    Catch ex As Exception

    Span1.InnerHtml = "Error saving file

    C:\\" & _

    File1.Value & "
    " & ex.ToS

    tring()

    End Try

    End If

    End Sub


  • 7/28/2019 Uploading Files Using the File Field Control

    9/16

    6/20/13 Uploading Files Using the File Field Control

    msdn.microsoft.com/en-us/library/aa478971.aspx 9/16

    C#

    void SubmitButton_Click(Object sender, EventA

    rgs e) {

    if (File1.PostedFile != null) {

    try {

    File1.PostedFile.SaveAs("C:\\Uploads

    \\uploadedfile.txt");

    Span1.InnerHtml = "Upload Successful

    !";

    }

    catch (Exception ex) {

    Span1.InnerHtml = "Error saving file

    C:\\" +

    File1.Value + "
    " + ex.ToS

    tring();

    }

    }

    }

  • 7/28/2019 Uploading Files Using the File Field Control

    10/16

    6/20/13 Uploading Files Using the File Field Control

    msdn.microsoft.com/en-us/library/aa478971.aspx 10/16


    This simple ASP.NET page uses validation controls so that

    the end user can only upload .mp3, .mpeg, or .m3u files

    to the server. If the file type is not one these three choices,

    a Validation control throws an exception onto the screen.

    This is shown in Figure 4.

    Figure 4. Validating the file type using validation

    controls

    Using validation controls is not a foolproof way of

    controlling the files that are uploaded to the server. It

    wouldn't be too hard for someone to change the file

    extension of a file so it would be accepted and uploaded to

    the server, thereby bypassing this simple security model.

    Uploading Multiple Files at the Same Time

    So far, you have seen some good examples of how to

    upload a file to the server without much hassle. Now let's

    take a look at how to upload multiple files to the server

    from a single page.

    No built-in capabilities in the Microsoft .NET Framework

    enable you to upload multiple files from a single ASP.NETpage. With a little work, however, you can easily accomplish

    this task.

    One trick is to import the System.IO class into your

    ASP.NET a e, and to then use the

  • 7/28/2019 Uploading Files Using the File Field Control

    11/16

    6/20/13 Uploading Files Using the File Field Control

    msdn.microsoft.com/en-us/library/aa478971.aspx 11/16

    HttpFileCollection class to capture all the files that

    are sent in with the Request object. This approach enables

    you to upload as many files as you want from a single

    page.

    For this example, you can build an ASP.NET page that has

    four file-input boxes and one Submit button. After the user

    clicks the Submit button and the files are posted to the

    server, the code behind takes the files and saves them to a

    specific location on the server. After the files are saved, the

    file information that was posted is displayed in the ASP.NET

    page (see Listing 3).

    Listing 3: Uploading multiple files to the server

    VB

    Sub SubmitButton_Click(Source As Object, e As

    EventArgs)

    Dim filepath As String = "C:\Uploads"

    Dim uploadedFiles As HttpFileCollection =

    Request.Files

    Dim i As Integer = 0

    Do Until i = uploadedFiles.CountDim userPostedFile As HttpPostedFile =

    uploadedFiles(i)

    Try

    If (userPostedFile.ContentLength > 0

    ) Then

    Span1.InnerHtml += "File #" &

    (i+1) & "
    "

    Span1.InnerHtml += "File Content

    Type: " & _

    userPostedFile.ContentType & "
    "

    Span1.InnerHtml += "File Size: "

    & _

    userPostedFile.ContentLength &

    "kb
    "

    Span1.InnerHtml += "File Name: "

    & _

    userPostedFile.FileName & ""

    userPostedFile.SaveAs(filepath &

    "\" & _

    Path.GetFileName(userPostedFil

    e.FileName))

  • 7/28/2019 Uploading Files Using the File Field Control

    12/16

    6/20/13 Uploading Files Using the File Field Control

    msdn.microsoft.com/en-us/library/aa478971.aspx 12/16

    Span1.InnerHtm += Locat on w er

    e saved: " & _

    filepath & "\" & _

    Path.GetFileName(userPostedFil

    e.FileName) & _

    "

    "

    End If

    Catch ex As Exception

    Span1.InnerHtml += "Error:
    " & ex

    .Message

    End Try

    i += 1

    Loop

    End Sub

    Select File1:


    Select File2:


    Select File3:


    Select File4:


    C#

    " "

  • 7/28/2019 Uploading Files Using the File Field Control

    13/16

    6/20/13 Uploading Files Using the File Field Control

    msdn.microsoft.com/en-us/library/aa478971.aspx 13/16

    =

    protected void SubmitButton_Click(Object send

    er, EventArgs e){

    string filepath = "C:\\Uploads";

    HttpFileCollection uploadedFiles = Request

    .Files;

    for (int i = 0; i < uploadedFiles.Count; i

    ++){

    HttpPostedFile userPostedFile = uploade

    dFiles[i];

    try

    {

    if (userPostedFile.ContentLength > 0

    )

    {

    Span1.InnerHtml += "File #" +

    (i+1) +"
    ";

    Span1.InnerHtml += "File Content

    Type: " +

    userPostedFile.ContentType + "


    ";

    Span1.InnerHtml += "File Size: "

    +

    userPostedFile.ContentLength +

    "kb
    ";

    Span1.InnerHtml += "File Name: "

    +

    userPostedFile.FileName + "";

    userPostedFile.SaveAs(filepath +

    "\\" +

    Path.GetFileName(userPostedFil

    e.FileName));

    Span1.InnerHtml += "Location wher

    e saved: " +

    filepath + "\\" +

    Path.GetFileName(userPostedFil

    e.FileName) +

    "

    ";

    }

    }

    catch (Exception Ex)

    {

    Span1.InnerText += "Error:
    " + E

    x.Message;

    }

    }

    }

  • 7/28/2019 Uploading Files Using the File Field Control

    14/16

    6/20/13 Uploading Files Using the File Field Control

    msdn.microsoft.com/en-us/library/aa478971.aspx 14/16

    Select File1:


    Select File2:


    Select File3:


    Select File4:


    The end user can select up to four files and click the

    Upload Files button, which initializes the

    SubmitButton_Click event. Using the

    HttpFileCollection class with the Request.Files

    property lets you gain control over all the files that are

    uploaded from the page. When the files are in this state,

    you can do whatever you want with them. In this case, thefiles' properties are examined and written to the screen. In

    the end, the files are saved to the Uploads folder in the

    root directory of the server. The result of this action is

    illustrated in Figure 5.

  • 7/28/2019 Uploading Files Using the File Field Control

    15/16

    6/20/13 Uploading Files Using the File Field Control

    msdn.microsoft.com/en-us/library/aa478971.aspx 15/16

    Figure 5. Uploading four files at once to the server from

    a single ASP.NET page

    As you may have noticed, one interesting point about this

    example is that the states of the file input text boxes are

    not saved with the postback. You can see this in Figure 5. In

    ASP.NET, the state of the file-input text boxes cannot be

    saved because doing so might pose a security risk.

    ConclusionThe File Field control provided by ASP.NET is a powerful

    control that was quite difficult to achieve in the days of

    Active Server Pages 3.0. This new capability allows your

    end-users to upload one or more files to your server.

    Remember, you can control the size of the files that are

    uploaded by working with settings in either the

    machine.config or web.config file.

    Related Books

    ASP.NET Professional Secrets

    http://shopping.msn.com/search/detail.aspx?pcId=12175&prodId=1525478&ptnrid=141&ptnrdata=0
  • 7/28/2019 Uploading Files Using the File Field Control

    16/16

    6/20/13 Uploading Files Using the File Field Control

    Microsoft Corporation. All rights reserved.

    2013 Microsoft. All rights reserved.

    http://msdn.microsoft.com/en-us/library/ms369863.aspx