ASP
  Home arrow ASP arrow ASP Upload Class
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
ASP

ASP Upload Class
By: Adrian Forbes
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 18
    2002-03-17

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    [bold]UploadClass.asp [/bold]


    <!pre>
    <!%
    ' Author: Adrian Forbes
    See UploadHelp.htm for usage instructions

    Class Upload
    Private sExtensions
    Private lMax
    Private iMode
    Private objFormobjFiles
    Private adVarCharadBooleanadIntegeradLongVarCharadDouble
    Private lDataLen
    Private sData
    Private sUploadPath

    Public Property Get UploadPath()
        
    UploadPath sUploadPath
    End Property

    Public Property Let UploadPath(sPath)
        
    sUploadPath sPath
        
    if ...[bold]UploadClass.asp [/bold]
    [
    code]
    <
    pre>
    <%
    ' Author: Adrian Forbes
    See UploadHelp.htm for usage instructions

    Class Upload
    Private sExtensions
    Private lMax
    Private iMode
    Private objFormobjFiles
    Private adVarCharadBooleanadIntegeradLongVarCharadDouble
    Private lDataLen
    Private sData
    Private sUploadPath

    Public Property Get UploadPath()
        
    UploadPath sUploadPath
    End Property

    Public Property Let UploadPath(sPath)
        
    sUploadPath sPath
        
    if strcomp(right(sUploadPath,1), "\") <> 0 then
            sUploadPath 
    sUploadPath "\"
        
    end if
    End Property

    Public Property Get FormCollection()
        
    Set FormCollection objForm
    End Property

    Public Property Get FilesCollection()
        
    Set FilesCollection objFiles
    End Property

    Public Property Get FormCount()
        
    FormCount objForm.Count
    End Property

    Public Property Get FileCount()
        
    FileCount objFiles.Count
    End Property

    Public Function Form(vIndex)
    Dim aData

        
    if IsNumeric(vIndexthen
            aData 
    objForm.Items
            Form 
    =     aData(vIndex 1)
        else
            if 
    objForm.Exists (vIndexthen
                Form 
    objForm.Item(vIndex)
            
    end if
        
    end if
        
    End Function

    Public Function 
    FormName(vIndex)
    Dim aData

        
    if IsNumeric(vIndexthen
            aData 
    objForm.Keys
            FormName 
    aData(vIndex 1)
        else
            if 
    objForm.Exists (vIndexthen
                FormName 
    vIndex
            end 
    if
        
    end if
        
    End Function

    Public Function 
    File(vIndex)
    Dim aData

        
    if IsNumeric(vIndexthen
            aData 
    objFiles.Items
            set File 
    aData(vIndex 1)
        else
            if 
    objFiles.Exists (vIndexthen
                set File 
    objFiles.Item(vIndex)
            
    end if
        
    end if
        
    End Function

    Public 
    Property Get ValidExtensions()
        
    ValidExtensions sExtensions
    End Property

    Public Property Let ValidExtensions(sExt)
        
    sExtensions sExt
    End Property

    Public Property Get MaxUploadSize()
        
    MaxUploadSize lMax
    End Property

    Public Property Let MaxUploadSize(lMaxUpload)
        
    lMax lMaxUpload
    End Property

    Public Property Get OverwriteMode()
        
    OverwriteMode iMode
    End Property

    Public Property Let OverwriteMode(iOWMode)
        
    iMode iOWMode
    End Property

    Public Property Get DataLength()
    DataLength lDataLen
    End Property

    Public Property Let DataLength(lBytes)
    lDataLen lBytes
    End Property

    Public Property Get RawData()
        
    RawData sData
    End Property

    Private Sub Class_Initialize()

        
    set objForm CreateObject("Scripting.Dictionary")
        
    set objFiles CreateObject("Scripting.Dictionary")

        
    ' Define the ADO constants, you can INCLUDE adoinc.vbs or reference
        ' 
    the type library instead if you want
        
        adVarChar 
    200
        adBoolean 
    11
        adInteger 
    3
        adLongVarChar 
    201
        adDouble 
    5

        owNoOverwrite 
    0    ' the upload will not overwrite an existing file of the same name
        owOverwrite = 1        ' 
    the upload will overwrite an existing file of the same name
        owUnique 
    2        ' if a file exists with the same name the uploaded file will be given a new, unique name

        sExtensions = ""
        lMax = 0
        iMode = 0
        
        UploadPath = Server.MapPath (".")
        
    end sub

    Private Sub Class_Terminate()
        objForm.RemoveAll
        set objForm = nothing

        objFiles.RemoveAll
        set objFiles = nothing

    End Sub

    Public Sub ProcessRequest
    Dim aData, iHeadPos, iPos, iDelimLen, iFileCount
    Dim objRS, sDelimeter, iHeadEnd, sHeader
    Dim lFormDataStart, lFormDataEnd, lSize
    Dim sFieldname, sPath, sFormData, bFile
    Dim objFSO, bExists, lCount, iFilenameStart
    Dim sFilename, lMIMEStart, lMIMEEnd, sMIME
    Dim objFile, bSave, sSaveAs, objUploadFile
    Dim tmpData, aFilename

        ' 
    Find out how much data is in the request    
    lDataLen 
    Request.TotalBytes

        
    ' Load the data into aData which will be a safe array
    aData = Request.BinaryRead(lDataLen)

        ' 
    The problem with this data is that VBScript can't manipulate the binary
        ' 
    data so we need to convert it into textThere are routines to do this,
        
    ' but we're going to get the Recordset object to do it for us
        
        
    if lenb(aData) > 0 then
            Set objRS 
    CreateObject("ADODB.Recordset"
            
            
    ' Append a field of type LongVarChar that is the length of our data
            objRS.Fields.Append "Data", adLongVarChar, lenb(aData)
            objRS.Open
        
            ' 
    Add a new record
            objRS
    .AddNew
        
            
    ' Insert the data into the field
            objRS("Data").AppendChunk aData
            objRS.Update
        
            ' 
    And then get it out as ASCII text!
            
    sData objRS("Data")
            
    set objRS nothing    
        
    else
            
    sData ""
        
    end if

        
    ' Clean up the array
        aData = ""

        ' 
    We want to find out the delimeter that separates each FORM item
        
    ' The delimeter will be the first line so look for the first CRLF
        ' 
    and the delimeter is everything before that CRLF
        iPos 
    Instr(sDatavbCRLF)
        if 
    iPos 0 then
            sDelimeter 
    left(sDataiPos 1)
        
    end if

        
    ' If the FORM is empty then there will have been no CRLF so sDelimeter will
        ' 
    be empty. Do a check just to make sure some data has been posted
        
    if len(sDelimeter) > 0 then
            
    ' We're going to keep track of our position through the datastarting at the start!
            
    iPos 1
            
    do
                
    ' Find the start of the delimeter
                iPos = Instr(iPos, sData, sDelimeter, 1)
                
                ' 
    Move past the delimeter and the CRLF to come to the header
                iPos 
    iPos len(sDelimeter vbCRLF)
                
                
    ' The header data ends with CRLFCRLF so find the position of the
                ' 
    next CRLFCRLFAdding 3 to this value means we get past the
                
    ' header and the trailing CRLFCRLF
                iHeadEnd = Instr(iPos, sData, vbCrLf & vbCrLf, 1) + 3

                ' 
    We know that iPos is the start of the header and iHeadEnd is the end
                
    ' so get the text inbetween
            sHeader = Mid(sData, iPos, iHeadEnd - iPos + 1)
            
                ' 
    The data starts at the position 1 after the header
            lFormDataStart 
    iHeadEnd 1
            
            
    ' The data ends with a CRLF and then the next delimeter so find out where
            ' 
    the delimeter is and subtract 3 which takes us before the CRLF and
            
    ' to the end of the data
            lFormDataEnd = Instr(lFormDataStart, sData, sDelimeter, 1) - 3

                ' 
    Calculate the size of the data
                lSize 
    lFormDataEnd lFormDataStart 1
                
                
    ' The name of the field is in the header'"name" fieldWe have written
                
    ' a small function called GetFieldData that reads the values of fields in
                ' 
    the header
                sFieldname 
    GetFieldData(sHeader"name"bExists)

                
    ' To find out if this FORM data is an uploaded file we want to search
                ' 
    the header for the presence of a filename header.
            
    sPath GetFieldData(sHeader"filename"bExists)

            
    ' If a filename has been found then we know it's a file
            
    if bExists then
                    bFile 
    true
        
                    iFilenameStart 
    0
                    sFilename 
    ""
                    
    aFilename Split(sPath,"\")
                    
                    if 
    UBound(aFilename) >= 0 then
                        sFilename 
    aFilename(UBound(aFilename))
                    else
                        
    sFilename ""
                    
    end if
                    
                    
    ' As it's a file we want to find the MIME typeThis is held in the Content-Type field
                    
    ' Find the start of the Content-Type field
                    lMIMEStart = Instr(1, sHeader, "Content-Type:", 1)
                    if lMIMEStart > 0 then
                        ' 
    Add 13 to this to get past Content-Type: and to the start of the data
                        lMIMEStart 
    lMIMEStart 13
                        
    ' Find the trailing vbCRLF
                        lMIMEEnd = Instr(lMIMEStart, sHeader, vbCRLF, 0)
                        if lMIMEEnd > 0 then
                            ' 
    Get the text in the middle
                            sMIME 
    trim(mid(sHeaderlMIMEStartlMIMEEnd lMIMEStart))
                        
    end if
                    
    end if
                else
                    
    ' If bExists returned false then it is not a file but a FROM element.
                ' 
    We know where the data starts and ends so let's get it. We only do
                ' 
    this if it isn't a file to aid performance as we will return to
                ' 
    save the files later on
                sFormData 
    mid(sDatalFormDataStartlFormDataEnd lFormDataStart 1)
                    
    bFile false
                end 
    if

                
    ' There is a collection of files and a collection of FORM elements, now that we
                ' 
    know what we are dealing with we can add to the appropriate collection (dictionary object)
                if 
    bFile then
                    
    ' If it is a file we want to create a new FileDetails class and store
                    ' 
    the relevant data inside it

                    set objFile 
    = New FileDetails
                        
                    objFile
    .Name sFieldName
                    objFile
    .Filename sFilename
                    objFile
    .OriginalPath sPath
                    objFile
    .Size lSize 1000
                    objFile
    .DataStart lFormDataStart
                    objFile
    .MIME sMIME

                    
    ' Add the class to the dictionary object
                    objFiles.Add sFieldName, objFile
                else
                    ' 
    Okhere is an HTTP "gotcha"There is nothing to stop you having
                    
    ' multiple items called the same thing. We want to search the already
                    ' 
    saved FORM items to see if this is a duplicate name.
                    if 
    objForm.Exists(sFieldNamethen
                        
    ' There is already an item in the objForm collection so we want to
                        ' 
    append to the existing entry rather than create a new one
                        
                        tmpData 
    objForm.Item(sFieldName)
                        
                        
    ' We now add the new field to the end of the existing one and
                        ' 
    separate the two with a comma.
                        
    ' So "ExistingData" will become "ExistingData,NewData"
                        objForm.Item(sFieldName) = tmpData & "," & sFormData
                    else
                        ' 
    This is a new FORM element so add a new entry to the collection
                        objForm
    .Add sFieldNamesFormData
                    end 
    if
                
    end if
                
    ' Now that FORM element has been processed let's move on to the next
                
    ' one. The next section is the end of the data for this one + 3. The
                ' 
    extra 3 is to take us past the CRLF that trails the data
                iPos 
    lFormDataEnd 3

            
    ' Now we want to know if there is another FORM element after this one. The
            ' 
    final element is followed by the delimeter and then "--"At this
            
    ' point iPos is pointing at the next delimeter, if that delimeter is
            ' 
    followed directly by "--" then we don't want to continue processing
            loop until (iPos = instr(iPos, sData, sDelimeter & "--", 1))

            ' 
    OKall the FORM elements (file and non-filehave been stored in the
            
    ' appropriate collection. We want to revisit all of the file elements and save
            ' 
    their data to diskThe reason we do it in this two-phase manner is so that
            
    ' we can contol the file saving process by elements in the FORM
            ' 
    dataI also feel it just makes for a neater and more flexible solution.
            
    Set objFSO CreateObject("Scripting.FileSystemObject")
            for 
    iFileCount 1 to objFiles.Count
                
    ' Get a handle on the instance of the FileDetails object in the collection
                set objFile = File(iFileCount)

                bSave = true

                ' 
    Check the size of the file to ensure it is below any limit
                
    ' we have set
                if lMax > 0 then
                    if cdbl(objFile.Size) > lMax then
                        bSave = false
                        ' 
    The file was bigger than the set limit so lets make that clear by
                        
    ' saying so in the SavedAs field. I just think it's a nice touch.
                        
    objFile.ErrorDescription "File exceeded size limit of " lMax
                    end 
    if
                
    end if

                
    ' Get the physical path to save the file to
                sPath = sUploadPath
                    
                ' 
    Get the original filename
                sFilename 
    objFile.Filename
                
                
    if len(trim(sFilename)) = 0 then
                    
    ' There is no filename so the user did not select a file to upload
                    bSave = false
                    objFile.ErrorDescription = "A file was not selected for uploading"
                else
                    ' 
    GetFilename will return the name we have to save the file to. If it returns empty
                    
    ' the file cannot be saved. This will only happen if the file already exists and iMode
                    ' 
    is owNoOverwrite
                    sFilename 
    GetFilename(sPathsFilenameiMode)
                    if 
    len(sFilename) = 0 then
                        bSave 
    false
                        objFile
    .ErrorDescription "A file of this name already exists and cannot be overwritten"
                    
    end if
                
    end if

                if 
    bSave then
                    
    ' We only want to save if the file's extension is in the list of valid extensions
                    
    if not IsValidExtension (sFilenamesExtensionsthen
                        bSave 
    false
                        objFile
    .ErrorDescription "The file's extension is invalid. Only these files can be uploaded: " sExtensions
                    end 
    if
                
    end if
                    
                if 
    bSave then

                    
    ' Find out the path of the file to save by appending the filename to the upload path
                    sSaveAs = sPath & sFilename

                    ' 
    The file size and extensions are all OK so we're ready to save.
                    ' 
    We saved the start position and length of the file data so let's use
                    ' 
    that to get the fileRemember that the size was previously
                    
    ' divided by 1000 to show the size in kbs so we have to multiply it
                    ' 
    by 1000 to get the real size again
                    sFormData 
    mid(sDataCdbl(objFile.DataStart), Cdbl(objFile.Size) * 1000)

                    
    ' Create the file and save the data to it
                    set objUploadFile = objFSO.CreateTextFile (sSaveAs, true)
                    objUploadFile.write sFormData
                    objUploadFile.close
                    set objUploadFile = nothing

                    ' 
    Now lets update the file object to show where the file was saved to
                    objFile
    .SavedAs sSaveAs
                end 
    if
            
    next
            set objFSO 
    nothing
        end 
    if

    End Sub

    Private Function GetFieldData(sTextsTargetByRef bHeaderExists)
    ' Extract the value from a named field in the header. The format is
    fieldname="fielddata"
    ' sText is the header, sTarget is the fieldname and the function returns fielddata
    Dim iPosS, iPosE

        bHeaderExists = False

        iPosS = instr(1, sText, sTarget & "=""")
        if iPosS < 1 then
            GetFieldData = ""
            exit function
        end if
        
        iPosS = iPosS + len(sTarget & "=""")
        iPosE = Instr(iPosS, sText, """")
        
        if iPosE < iPosS then
            GetFieldData = ""
            exit function
        end if

        GetFieldData = mid(sText, iPosS, iPosE - iPosS)

        bHeaderExists = True

    End Function

    function GetFilename(ByVal sPath, ByVal sFilename, ByVal iMode)
    This function will return the name of the file to be created
    ' If the file cannot be created then it returns an empty string
    dim objFSO, lIndex, bFound, sTempFilename, sFile, iPos, sExt

        select case iMode
        case owOverwrite
            ' 
    We are using overwrite mode so it doesn't matter if the file
            ' 
    already exists
            GetFilename 
    sFilename
        
    case owNoOverwrite
            
    ' We are not in overwritw mode so check to see if the
            ' 
    file exists
            set objFSO 
    CreateObject("Scripting.FileSystemObject")
            if 
    objFSO.FileExists (sPath sFilenamethen
                
    ' It does so return an empty string
                GetFilename = ""
            else
                ' 
    It doesn't so return the filename as it's OK to save.
                
    GetFilename sFilename
            end 
    if
            
    set objFSO nothing
        
    case owUnique
            
    ' Unique mode means that the file will be saved but amended
            ' 
    if neccessary so that it doesn't overwrite existing files
            set objFSO = CreateObject("Scripting.FileSystemObject")
            
            ' 
    First check to see if the file exists, if it doesn't things
            ' 
    are nice and simple
            
    if objFSO.FileExists (sPath sFilenamethen
                
    ' The file already exists so we need to find a new name for it
                ' 
    First of all split it up into its name and extension
                sFile 
    sFilename
                sExt 
    ""
                
    for iPos len(sFilenameto 1 step -1
                    
    If Strcomp(Mid(sFilenameiPos1), ".") = 0 Then
                        sFile 
    left(sFilenameiPos 1)
                        
    sExt mid(sFilenameiPos+1)
                        exit for
                    
    end if
                
    next
                
                
    ' We will get a unique name by adding a number in parenthesis until
                ' 
    we get a unique nameSo for file.txt we will try file(2).txt
                
    ' then file(3).txt and so on
                bFound = false
                lIndex = 2
                while not bFound
                    sFilename = sFile & "(" & lIndex & ")." & sExt
                    if objFSO.FileExists(sPath & sFilename) then
                        lIndex = lIndex + 1
                    else
                        bFound = true
                    end if
                wend
                set objFSO = nothing
                ' 
    Return the new, unique filename
                GetFilename 
    sFilename
            
    else
                
    ' The file doesn't exists so it can keep its name
                GetFilename 
    sFilename
            end 
    if
            
    set objFSO nothing
        end select
    end 
    function

    function 
    IsValidExtension(byval sFilenamebyval sValidExtensions)
    ' Given a filename and comma separated list of valid extensions this
    function checks that the filename has an extension that appears
    ' in the valid list
    dim iPos, sExt, aExt, iIndex

        if len(trim(sValidExtensions)) = 0 then
            IsValidExtension = true
            exit function
        end if

        sFilename = Trim(sFilename)
        for iPos = len(sFilename) to 1 step -1
            If Strcomp(Mid(sFilename, iPos, 1), ".") = 0 Then
                sExt = mid(sFilename, iPos+1)
                aExt = split(sValidExtensions, ",")
                for iIndex = lbound(aExt) to ubound(aExt)
                    if strcomp(trim(aExt(iIndex)), sExt, 1) = 0 then
                        IsValidExtension = true
                        exit function
                    end if
                next
            end if
        next

        IsValidExtension = false
        
    end function

    end class

    Class FileDetails
    This class is simply a glorified UDT to store data about each fileAn instance
    ' of this class for each submitted file will be stored in a dictionary object
    Private sFormName
    Private sFileName
    Private lFileSize
    Private sOriginalPath
    Private lDataStart
    Private sMIME
    Private sError
    Private bSaved
    Private sSavedAs

    Public Property Get SavedAs()
        SavedAs = sSavedAs
    End Property

    Public Property Let SavedAs(sFile)
        sSavedAs = sFile
        bSaved = True
    End Property

    Public Property Get Saved()
        Saved = bSaved
    End Property

    Public Property Let Saved(bVal)
        bSaved = bVal
    End Property

    Public Property Get ErrorDescription()
        ErrorDescription = sError
    End Property

    Public Property Let ErrorDescription(sDesc)
        sError = sDesc
    End Property

    Public Property Get MIME()
        MIME = sMIME
    End Property

    Public Property Let MIME(sType)
        sMIME = sType
    End Property

    Public Property Get DataStart()
        DataStart = lDataStart
    End Property

    Public Property Let DataStart(lStart)
        lDataStart = lStart
    End Property

    Public Property Get OriginalPath()
        OriginalPath = sOriginalPath
    End Property

    Public Property Let OriginalPath(sPath)
        sOriginalPath = sPath
    End Property

    Public Property Get Size()
        Size = lFileSize
    End Property

    Public Property Let Size(lSize)
        lFileSize = lSize
    End Property

    Public Property Get Filename()
        Filename = sFileName
    End Property

    Public Property Let Filename(sFile)
        sFileName = sFile
    End Property

    Public Property Get Name()
        Name = sFormName
    End Property

    Public Property Let Name(sName)
        sFormName = sName
    End Property

    Private Sub Class_Initialize()
        bSaved = False
    End Sub

    End Class

    %>
    </pre>

    [bold]Uploadhelp.asp [/bold][bold]Properties[/bold][bold]UploadPath[/bold]The physical path the uploaded files will be saved toobjUpload.UploadPath = "c:\uploads\"objUpload.UploadPath = Server.MapPath "/images/" [bold]FormCollection[/bold]The dictionary object containing the FORM dataSet objForm = objUpload.FormCollection [bold]FilesCollection[/bold]The dictionary object containing a collection of FileDetails classesSet objFiles = objUpload.FilesCollection [bold]FormCount[/bold]Number of non-file items posted with the Form Response.Write objUpload.FormCount [bold]FileCount[/bold]Number of file items posted with the Form Response.Write objUpload.FileCount [bold]ValidExtensions[/bold]A comma separated list of valid extensions objUpload.ValidExtensions = "jpg,gif,bmp,tif,tiff" [bold]MaxUploadSize[/bold]The maximum size, in bytes, that files are allowed to be objUpload.MaxUploadSize = 2048 [bold]OverwriteMode[/bold]This defines how to treat the saving of files that already exist. Type Value Description NoOverwrite 0 (default) The file is not saved if one of the same name already exists Overwrite 1 If a file of the same name already exists then it is overwritten with the uploaded Unique 2 If a file of the same name already exists then the uploaded file is renamed to be unique. For example test.txt will become test(1).txt objUpload.OverwriteMode = 1 [bold]DataLength[/bold]The size of the raw POST data. Only available after a call to ProcessRequest Response.Write objUpload.DataLength [bold]RawData[/bold]The raw POST data. Only available after a call to ProcessRequest Response.Write "
    " & objUpload.RawData & 
    " [bold]Functions[/bold][bold]ProcessRequest[/bold]Save uploaded files to disk and construct the Form and Files collections objUpload.ProcessRequest [bold]Form(vIndex)[/bold]Returns the content of a Form item. vIndex can be a numerical index (1 based) or the textual name Response.Write "Hello " & objUpload.Form("txtName")Response.Write "Hello " & objUpload.Form(1) [bold]FormName(vIndex)[/bold]Returns the name of the Form item. vIndex can be a numerical index (1 based) or the textual name Response.Write "The value of " & objUpload.FormName(1) & " is " & objUpload.Form(1) [bold]File(vIndex)[/bold]Returns the instance of the FileDetails class for a given file. vIndex can be a numerical index (1 based) or the textual name Set objFile = objUpload.File(1) The properties of the File object areProperty Type Description Name String The name of the FORM field the file was submitted from Filename String The name of the file Size Double The size of the file in Kb OriginalPath String The full path and name of the file on the client's file system DataStart Long The location of the start of the data in the POST. This value is used internally. MIME String The MIME type of the file Saved Boolean True if the file was successfully saved, False if not SavedAs String If the file was saved, this is the full path and filename of the file ErrorDescription String If the file was not saved this contains the reason why [bold]Usage examples[/bold]Getting details on all of the files uploaded


    <table border="1">
    <
    tr>
    <
    td>Name</td><td>Filename</td><td>Size (kb)</td><td>Saved?</td>
    <
    td>MIME Type</td><td>Original Path</td><td>Saved As</td>
    </
    tr>
    <%
    for 
    1 to objUpload.FileCount
        set objFile 
    objUpload.File(i)

        
    Response.Write "<tr><td>" objFile.Name "</td>" vbCRLF
        Response
    .Write "<td>" objFile.Filename "</td>" vbCRLF
        Response
    .Write "<td>" objFile.Size "</td>" vbCRLF
        Response
    .Write "<td>" objFile.Saved
        
    if objFile.Saved then
            Response
    .Write "</td>" vbCRLF
        
    else
            
    Response.Write "
    objFile.ErrorDescription "</td>" vbCRLF
        end 
    if
        
    Response.Write "<td>" objFile.MIME "</td>" vbCRLF
        Response
    .Write "<td>" objFile.OriginalPath "</td>" vbCRLF
        Response
    .Write "<td>" objFile.SavedAs "</td>" vbCRLF
        Response
    .Write "</tr>" vbCRLF
    next
    %>
    </
    table

    Getting details on all of the form elements submitted


    <table border="1">
    <
    tr><td>Name</td><td>Value</td></tr>
    <%
    for 
    1 to objUpload.FormCount
        Response
    .Write "<tr><td>" objUpload.FormName(i) & "</td>" vbCRLF
        Response
    .Write "<td>" objUpload.Form(i) & "</td>" vbCRLF
        Response
    .Write "</tr>" vbCRLF
    next
    %>
    </
    table

    [bold]UploadReceive.asp [/bold]


    <%@ Language=VBScript %>
    <%
    option explicit%>
    <%
    server.ScriptTimeout 600%>
    <
    html>
    <
    head>
    <
    title>Pure ASP upload</title>
    <
    META NAME="Author" Content="Adrian Forbes">
    </
    head>
    <!-- 
    #Include File="uploadclass.asp" -->
    <body>
    <
    pre>
    <%
    ' See UploadHelp.htm for usage instructions

        Dim owNoOverwrite, owOverwrite, owUnique
        Dim objUpload
        
        Set objUpload = New Upload
        
        ' 
    If we want to limit the size of uploads set the lMax value to the
        
    ' max amount of kb we want to load. 2048 is 2mb. For no limit set
        ' 
    this to 0

        
    'objUpload.MaxUploadSize = 2048
        
        ' 
    If we want to limit the type of files to upload add the extensions of valid
        
    ' files to sExtensions as a comma separated list. If you don't want to
        
    ' limit the extensions simply make the variable blank ("")
        
        '
    objUpload.ValidExtensions "zip,txt,jpg,gif"
        
        ' Define the overwrite constants

        owNoOverwrite = 0    ' 
    the upload will not overwrite an existing file of the same name
        owOverwrite 
    1        ' the upload will overwrite an existing file of the same name
        owUnique = 2        ' 
    if a file exists with the same name the uploaded file will be given a new, unique name

        
    ' Set the overwrite mode
        
        objUpload.OverwriteMode = owOverwrite

        ' 
    Set the path we want the files to be saved to. If this is not
        
    ' supplied it defaults to the directory that the page is in
        
        objUpload.UploadPath = server.MapPath (".")
        
        ' 
    Do the work
        
        objUpload
    .ProcessRequest
        
        
    ' We're going to see if the "raw data" checkbox has been checked, if so
        
    ' display the raw post. This will help you understand what is going on.
        if len(trim(objUpload.Form("chkRaw"))) > 0 then
            Response.Write "<p>Data (" & objUpload.DataLength & " bytes): <pre>" & objUpload.RawData
            Response.Write vbCRLF & "</pre>
    <hr>"
        end if
    %>

    <h2>File results</h2>

    <table border="1" cellpadding=5>
    <tr><td>Name</td><td>Filename</td><td>Size (kb)</td><td>Saved?</td><td>MIME Type</td><td>Original Path</td><td>Saved As</td></tr>
    <%
    OKat this stage we have an instance of the Upload class (objUploadwhich exposes two collections,
    '
     one for files and one for FORM data
    Dim i, objFile

    for i = 1 to objUpload.FileCount
        set objFile = objUpload.File(i)

        Response.Write "<tr><td>" & objFile.Name & "</td>" & vbCRLF
        Response.Write "<td>" & objFile.Filename & "</td>" & vbCRLF
        Response.Write "<td>" & objFile.Size & "</td>" & vbCRLF
        Response.Write "<td>" & objFile.Saved
        if objFile.Saved then
            Response.Write "</td>" & vbCRLF
        else
            Response.Write "
    " & objFile.ErrorDescription & "</td>" & vbCRLF
        end if
        Response.Write "<td>" & objFile.MIME & "</td>" & vbCRLF
        Response.Write "<td>" & objFile.OriginalPath & "</td>" & vbCRLF
        Response.Write "<td>" & objFile.SavedAs & "</td>" & vbCRLF
        Response.Write "</tr>" & vbCRLF
    next
    %>
    </table>

    <h2>Form results</h2>
    <table border="1" cellpadding=5>
    <tr><td>Name</td><td>Value</td></tr>
    <%
    for i = 1 to objUpload.FormCount
        Response.Write "<tr><td>" & objUpload.FormName(i) & "</td>" & vbCRLF
        Response.Write "<td>" & objUpload.Form(i) & "</td>" & vbCRLF
        Response.Write "</tr>" & vbCRLF
    next
    %>
    </table>
    <%
    set objUpload = nothing
    %>
    </pre>
    </body>
    </html>

    [bold]UploadSend.asp [/bold]


    <p>
    This is a test FORMWe will POST two text boxestwo filestwo checkboxes
    and a textareaThe checkboxes have the same name.
    <
    FORM ACTION="UploadReceive.asp" METHOD="POST" ENCTYPE="multipart/form-data">
    <
    input type=checkbox name=chkRaw value="Yes">Show raw data

    <input type=text name=txtData1>

    <INPUT TYPE=FILE NAME="UploadFormName1">

    <input type=text name=txtData2>

    <INPUT TYPE=FILE NAME="UploadFormName2">

    <textarea name=txtTextArea rows="5" cols="70"></textarea>


    <input type=checkbox name=chkTest value="Yes">Test checkbox

    <input type=checkbox name=chkTest value="No">Test checkbox

    <INPUT TYPE="SUBMIT">

    </
    FORM>


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More ASP Articles
    More By Adrian Forbes

     

    IBM® developerWorks developerWorks - FREE Tools!


    NEW! Best practices for software analysis: An introduction to the IBM Rational Software Analyzer application

    This whitepaper presents the benefits of successfully introducing static analysis into your organization using IBM Rational Software Analyzer. Additionally, it identifies some common pitfalls that can hinder the effective use of static analysis tooling as well as presents 10 simple strategies designed to help you quickly realize the value of static analysis using Rational Software Analyzer.
    FREE! Go There Now!


    NEW! BlammoSplat: Build a community Web site of OpenLaszlo animations, Part 3: The community animation

    Learn to enable users to both rate existing animations and to combine existing animations into new snippets. This is the third in a series of three tutorials that chronicle the building of a site that enables collaborative discussion and animation building using Domino and OpenLaszlo.
    FREE! Go There Now!


    NEW! Download a free trial of Lotus Quickr 8.0

    Visit IBM developerWorks to download a free trial version of Lotus Quickr 8.0, which enables collaboration by transforming the way everyday business content such as documents, rich media, photos, and video can be shared. Lotus Quickr makes it faster and easier to share content of all types (not just documents) within virtual teams. It is designed to make it easier to collaborate across organizational boundaries, while continuing to work within the context of familiar desktop applications.
    FREE! Go There Now!


    NEW! Evaluate IBM Lotus Sametime Standard V8.0

    Visit IBM developerWorks to download a free trial of the latest release of IBM Lotus Sametime Standard V8.0. Lotus Sametime Standard V8.0 is a platform for unified communications and collaboration that combines security features with an extensible, open solution including integrated Voice over IP, geographic location awareness, mobile clients, and a robust Business Partner community offering telephony and video integration.
    FREE! Go There Now!


    NEW! Hello World: WebSphere Service Registry and Repository

    Manage, govern, and share services across your organization by using WebSphere Service Registry and Repository. Follow the hands-on exercises to learn how to navigate the Web interface to publish, find, reuse, and update services.
    FREE! Go There Now!


    NEW! IBM Enterprise Modernization Sandbox for System z

    IBM Enterprise Modernization solutions help organizations evolve core IT systems towards modern architectures and technologies—reducing the burden of maintenance and freeing up resources to develop new business requirements and capabilities. With the IBM Enterprise Modernization Sandbox for System z you can evaluate IBM Enterprise Modernization solutions focused on five key areas: Assets, Architectures, Skills, Processes and Infrastructures, and Investment. Each solution is based upon real customer experiences and offers a proven path to get you started with your modernization projects.
    FREE! Go There Now!


    NEW! IBM Rational Systems Development e-Kit

    As systems increase in complexity, communication between systems and software teams becomes more and more difficult. Now, there’s a way to improve product quality and communication.<br />Read the “Model Driven Systems Development” white paper to see how. Also included in this kit are more educational white papers, customer examples, tutorials, informative Webcasts, and best practices for designing, building and managing systems.<br />
    FREE! Go There Now!


    NEW! Rational Talks to You: Manage RUP-based CMMI initiatives

    Join this Rational Talks to You teleconference on December 4 at 1:00 pm ET to discuss how Rational Method Composer can help meet your compliance objectives. Get your questions answered!
    FREE! Go There Now!


    NEW! Webcast: Calling All Testers! Find Application Vulnerabilities Early in the Development Process Where they are Easier to Fix and Less Risky to your Business

    In this webcast, IBM Rational will discuss the importance of Web application security and will share techniques and best practices to introduce application security testing into current QA processes including: understanding common security vulnerabilities and techniques to integrate security testing with defect tracking and remediation systems in an effort to safeguard sensitive online information.
    FREE! Go There Now!


    NEW! Webcast: Quickly provide customized, integrated user interfaces with Lotus Notes 8

    IBM Lotus Notes 8 provides a wide range of developers the ability to provide customized, integrated user interfaces via composite applications and via custom sidebar and toolbar plug-ins. This webcast provides you with tips and techniques to use with out-of-the-box capabilities of Lotus Notes 8, and survey how you can share useful components within your own company and within a larger community.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    ASP ARTICLES

    - Using MySQL with ASP
    - ADO for the Beginner
    - ADO.NET 101: Data Rendering with a DataGrid ...
    - Introducing SoftArtisans OfficeWriter 3.0 En...
    - Getting Remote Files With ASP
    - The Real Basics of Functions in ASP
    - Enhancing Readability with ASP
    - Mimicking PHP's String Formatting Functions
    - Windows Server Hacks 12, 77, and 98
    - How to Sort a Multi-Dimensional Array
    - Developing an Information Management Tool wi...
    - What are Active Server Pages?
    - Getting Remote Pages with ASP
    - FTP’ing Files with ASP
    - Apply Single-Sign-On to Your Application





    © 2003-2010 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek