Home     Products      Support      Corporate     Sign In 
Support Knowledge Base, Article 1132
Product
FileUp
Version
version 5 and higher
Title
Using FileUp in a .NET user control
Problem
By using FileUp in a .NET user control, you can create a re-usable upload form that can be added to a page by registering the control. The following serves as an example for using FileUp with the httpModule in a .NET user control (*.ascx)
Solution

The following example is written in VB.NET. It is designed to use FileUp's HttpModule so that server performance will not be hindered by potentially large uploads.

The design of this user control will include the entire upload form. This is because <FORM> element must have the following attributes in order to be RFC-1867 compliant (which FileUp requires):

  • ENCTYPE must be set to "MULTIPART/FORM-DATA"
  • METHOD must be set to "POST". This does not need to be explicitly declared in a .NET form that runs server-side, as the METHOD attribute is automatically assumed to be "POST".

The form will also contain a button to trigger the postback necessary to send files to the server. The code that will instantiate FileUp is in the code-behind of the user-control.

Instructions:

  1. Create a VisualStudio.Net ASP.NET web project(VB) and name it "FileUpUserControl".

  2. Add FileUp (safileup.dll) and the FileUp HttpModule (FileUpModule.dll) as references to your Visual Studio.NET project. (Note: Since FileUp is a COM component, and not a pure .NET component, you must remember to add a reference to the same version of the dll that is registered on your server.)

  3. Set up your web.config/machine.config file for the use of FileUp's HttpModule, and set appropriate security on the directories to which FileUp will cache and save files. This KB article assumes familiarity with these topics, but should you need more information on the HttpModule and using FileUp in a .NET environment, please see the online FileUp documentation. Please see the "Installation Instructions" for configuring the HttpModule as well as the section on "Security Considerations" for setting appropriate security for caching and upload directories.

  4. Create the web form in the *.ascx page. This is the form that you use to select the file for uploading.

    FileUpWebUserControl.ascx
    
    <%@ Control Language="vb" AutoEventWireup="false" Codebehind="FileUpWebUserControl.ascx.vb" 
    Inherits="FileUpUserControl.FileUpWebUserControl" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
    
    <FORM id="theForm" runat="server" ENCTYPE="multipart/form-data" >
    	<TABLE WIDTH="600" align="center">
    		<TR>
    			<TD ALIGN="right" VALIGN="top">Enter Filename:</TD>
    			<!-- Note: Notice this form element is of TYPE="FILE"-->
    			<TD ALIGN="left">
    				<INPUT TYPE="file" NAME="myFile"><BR>
    				<I>Click "Browse" to select a file to upload</I>
    			</TD>
    		</TR>
    		<TR>
    			<TD ALIGN="right"> </TD>
    			<TD ALIGN="left"><INPUT TYPE="button" id="UploadBtn" 
                                runat="server" OnServerClick="UploadBtn_Click" VALUE="Upload File"
    					NAME="UploadBtn"></TD>
    		</TR>
    		<TR>
    			<TD colspan="2">
    				<HR noshade>
    				<B>Note:</B> This sample demonstrates how to perform a simple single file 
    				upload with FileUp
    			</TD>
    		</TR>
    	</TABLE>
    </FORM>
    <ASP:LITERAL id="ltrUploadResults" runat="Server" />
    


  5. Instantiate FileUp in the code behind of the *.ascx page. FileUp will pare out the files from the POST request made by the web form.

    FileUpWebUserControl.ascx.vb
    
    Imports System
    Imports SoftArtisans.Net
    Public Class FileUpWebUserControl
        Inherits System.Web.UI.UserControl
    
    #Region " Web Form Designer Generated Code "
    
        'This call is required by the Web Form Designer.
        <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
    
        End Sub
        Protected WithEvents UploadBtn As System.Web.UI.HtmlControls.HtmlInputButton
    
        'NOTE: The following placeholder declaration is required by the Web Form Designer.
        'Do not delete or move it.
        Private designerPlaceholderDeclaration As System.Object
    
        Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
            'CODEGEN: This method call is required by the Web Form Designer
            'Do not modify it using the code editor.
            InitializeComponent()
        End Sub
    
    #End Region
    
        '--- Declare controls used on the webform
        Protected theForm As System.Web.UI.HtmlControls.HtmlForm
        Protected ltrUploadResults As System.Web.UI.WebControls.Literal
    
    
        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            ' Put user code to initialize the page here
    
        End Sub
        Protected Sub UploadBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
            '--- Hide the form when the upload button is clicked
            theForm.Visible = False
            ProcessUpload()
    
        End Sub
    
        Private Sub ProcessUpload()
    
            '--- Instantiate the FileUp object
            Dim oFileUp As New FileUp(Context)
    
            '--- This StringBuilder will be used to display results
            Dim results As New System.Text.StringBuilder
    
            Try
    
                oFileUp.Path = "C:\Save Here"
    
                '--- Check to be sure there was a file selected in the form
                '--- If so, continue processing
    
                '--- Get a reference to the uploaded file field
                Dim oFile As SaFile = CType(oFileUp.Form("myFile"), SaFile)
    
                If Not (oFile Is Nothing) Then
                    If Not (oFile.IsEmpty) Then
    
                        '--- Save the file
                        '--- Note: The Save() method saves the file
                        '--- with its original name to the directory
                        '--- you set as the Path property.
                        '--- To save a file to a different location
                        '--- or with a different name, use the SaveAs() method
                        '--- instead of Save()
                        oFile.Save()
    
                        '--- Display information about the saved file
                        results.Append("<H3>FileUp Saved the File Successfully</H3>")
                        results.Append("<DL>")
    
                        '--- ServerName is the full path of the file as it was saved on the server
                        results.Append("<DT><B>Path on server</B></DT><DD>" + oFile.ServerName + "</DD>")
                        '--- UserFilename is the full path of the file as it was sent from the client
                        results.Append("<DT><B>Path on client</B></DT><DD>" + oFile.UserFilename + "</DD>")
                        '--- ShortFileName is just the Userfilename without the path
                        results.Append("<DT><B>Short filename</B></DT><DD>" + oFile.ShortFilename + "</DD>")
                        '--- TotalBytes is the byte size of the file
                        results.Append("<DT><B>Byte size</B></DT><DD>" + oFile.TotalBytes.ToString() + "</DD>")
                        '--- ContentType is the mime type of the file. Eg, "application/msword"
                        results.Append("<DT><B>Content type</B></DT><DD>" + oFile.ContentType + "</DD>")
                        '--- CheckSum is the MD5 hash of the file that can be used to check file integrity
                        results.Append("<DT><B>CheckSum</B></DT><DD>" + oFile.Checksum + "</DD>")
                        results.Append("</DL>")
    
                    Else
                        '--- If SaFile.IsEmpty is true, the file field was left empty
                        results.Append("There was no file submitted in the form field.")
                    End If
                Else
                    results.Append("The referenced field does not exist or is not of type=""file""")
                End If
    
                '--- Display the results on the webform
                ltrUploadResults.Text = results.ToString()
    
            Catch ex As System.Exception
                '--- If an exception is caught, display the details
                ltrUploadResults.Text = "<b>An error has occurred:</b><br>" + _
                       ex.Message
            Finally
                '--- Always call FileUp.Dispose in the finally block
                If Not (oFileUp Is Nothing) Then
                    oFileUp.Dispose()
                End If
                oFileUp = Nothing
            End Try
    
        End Sub
    
    End Class
    


  6. Create the parent *.aspx page. This is the page that loads the user control as part of its content. Make sure the parent *.aspx page gets converted to a *.uplx page when you are done writing the code for this page. Leaving it as *.aspx lets you take advantage of VS.NET's intellisense during the design process, but in order to use the httpModule in production, the extension must be changed to *.uplx.

    ParentForm.uplx
    
    <%@ Page Language="vb" AutoEventWireup="false" Codebehind="ParentForm.uplx.vb" %>
    <%@ Register tagprefix="FileUpCode" tagname="UploadForm" src="FileUpWebUserControl.ascx" %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
    	<HEAD>
    		<TITLE>WebForm1</TITLE>
    		<META name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
    		<META name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
    		<META name="vs_defaultClientScript" content="JavaScript">
    		<META name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    	</HEAD>
    	<BODY MS_POSITIONING="GridLayout">
    		<FileUpCode:UploadForm runat="server" />
    	</BODY>
    </HTML>
    


Created : 7/22/2005 2:01:37 PM (last modified : 4/24/2012 4:09:13 PM)
Rate this article!
 
Comments