User Login





Register
Forget Password

Hostings with very low prices

Hosting Plans Starting at 1$/Month

BaydHost

Powered By

  • AhmBay
  • Uploading Files to the Server Hard Disk using plain ASP - ASP Webmaster Tips, Knowledge Base Webmaster Tools

    Home > ASP > Uploading Files to the Server Hard Disk using plain ASP
    Category: ASP
    Written by: Admin
    Date: 2008-11-10
    Rating: 0   Puan:0 | Katılımcı:0 | Voted : 0 times
    Hit: 39
      

    This article is number three in a series of articles I wrote about uploading and displaying binary data with ASP. The first article was about Uploading binary data to the database, second was on Displaying binary data from the database and the third one ( this one ) is going to be on 'Uploading files to the server hard disk using pure ASP'.



    File Uploading with ASP.NET
    If you have the privilege of using ASP.NET then you should read these comprehensive tutorials regarding file uploading using built-in ASP.NET server controls:



    File uploading to server hard disk.
    File uploading to Microsoft Access database.
    Uploading images, determining size, width & height and resizing image files.


    I'll assume that you have read the previous articles and thus will only concentrate on the parts which are new in this article. I get enormous amounts of emails by people asking me how to upload files with ASP. This article is going to be an answer to all those questions.



    In all the previous articles we have been using Loader.asp to handle binary data. Same is going to be the case in this article. We'll though modify Loader.asp a bit to allow us to save uploaded binary data to the server hard disk.



    Loader.asp
    Open your note pad ( or any other ASP editor you use ) and create a new file. Save it as 'Loader.asp'. Now copy the text listed below and paste it in to the newly created 'Loader.asp' page and hit the save button :



    Open your note pad ( or any other ASP editor you use ) and create a new file. Save it as 'Loader.asp'. Now copy the text listed below and paste it in to the newly created 'Loader.asp' page and hit the save button :


    <%
    ' -- Loader.asp --
    ' -- version 1.5.2
    ' -- last updated 12/5/2002
    '
    ' Faisal Khan
    ' faisal@stardeveloper.com
    ' www.stardeveloper.com
    ' Class for handling binary uploads

    Class Loader
    Private dict

    Private Sub Class_Initialize
    Set dict = Server.CreateObject("Scripting.Dictionary")
    End Sub

    Private Sub Class_Terminate
    If IsObject(intDict) Then
    intDict.RemoveAll
    Set intDict = Nothing
    End If
    If IsObject(dict) Then
    dict.RemoveAll
    Set dict = Nothing
    End If
    End Sub

    Public Property Get Count
    Count = dict.Count
    End Property

    Public Sub Initialize
    If Request.TotalBytes > 0 Then
    Dim binData
    binData = Request.BinaryRead(Request.TotalBytes)
    getData binData
    End If
    End Sub

    Public Function getFileData(name)
    If dict.Exists(name) Then
    getFileData = dict(name).Item("Value")
    Else
    getFileData = ""
    End If
    End Function

    Public Function getValue(name)
    Dim gv
    If dict.Exists(name) Then
    gv = CStr(dict(name).Item("Value"))

    gv = Left(gv,Len(gv)-2)
    getValue = gv
    Else
    getValue = ""
    End If
    End Function

    Public Function saveToFile(name, path)
    If dict.Exists(name) Then
    Dim temp
    temp = dict(name).Item("Value")
    Dim fso
    Set fso = Server.CreateObject("Scripting.FileSystemObject")
    Dim file
    Set file = fso.CreateTextFile(path)
    For tPoint = 1 to LenB(temp)
    file.Write Chr(AscB(MidB(temp,tPoint,1)))
    Next
    file.Close
    saveToFile = True
    Else
    saveToFile = False
    End If
    End Function

    Public Function getFileName(name)
    If dict.Exists(name) Then
    Dim temp, tempPos
    temp = dict(name).Item("FileName")
    tempPos = 1 + InStrRev(temp, "\")
    getFileName = Mid(temp, tempPos)
    Else
    getFileName = ""
    End If
    End Function

    Public Function getFilePath(name)
    If dict.Exists(name) Then
    Dim temp, tempPos
    temp = dict(name).Item("FileName")
    tempPos = InStrRev(temp, "\")
    getFilePath = Mid(temp, 1, tempPos)
    Else
    getFilePath = ""
    End If
    End Function

    Public Function getFilePathComplete(name)
    If dict.Exists(name) Then
    getFilePathComplete = dict(name).Item("FileName")
    Else
    getFilePathComplete = ""
    End If
    End Function

    Public Function getFileSize(name)
    If dict.Exists(name) Then
    getFileSize = LenB(dict(name).Item("Value"))
    Else
    getFileSize = 0
    End If
    End Function

    Public Function getFileSizeTranslated(name)
    If dict.Exists(name) Then
    temp = LenB(dict(name).Item("Value"))
    If temp <= 1024 Then
    getFileSizeTranslated = temp & " bytes"
    Else
    temp = FormatNumber((temp / 1024), 2)
    getFileSizeTranslated = temp & " kilobytes"
    End If
    Else
    getFileSizeTranslated = ""
    End If
    End Function

    Public Function getContentType(name)
    If dict.Exists(name) Then
    getContentType = dict(name).Item("ContentType")
    Else
    getContentType = ""
    End If
    End Function

    Private Sub getData(rawData)
    Dim separator
    separator = MidB(rawData, 1, InstrB(1, rawData, ChrB(13)) - 1)

    Dim lenSeparator
    lenSeparator = LenB(separator)

    Dim currentPos
    currentPos = 1
    Dim inStrByte
    inStrByte = 1
    Dim value, mValue
    Dim tempValue
    tempValue = ""

    While inStrByte > 0
    inStrByte = InStrB(currentPos, rawData, separator)
    mValue = inStrByte - currentPos

    If mValue > 1 Then
    value = MidB(rawData, currentPos, mValue)

    Dim begPos, endPos, midValue, nValue
    Dim intDict
    Set intDict = Server.CreateObject("Scripting.Dictionary")

    begPos = 1 + InStrB(1, value, ChrB(34))
    endPos = InStrB(begPos + 1, value, ChrB(34))
    nValue = endPos

    Dim nameN
    nameN = MidB(value, begPos, endPos - begPos)

    Dim nameValue, isValid
    isValid = True

    If InStrB(1, value, stringToByte("Content-Type")) > 1 Then

    begPos = 1 + InStrB(endPos + 1, value, ChrB(34))
    endPos = InStrB(begPos + 1, value, ChrB(34))

    If endPos = 0 Then
    endPos = begPos + 1
    isValid = False
    End If

    midValue = MidB(value, begPos, endPos - begPos)
    intDict.Add "FileName", trim(byteToString(midValue))

    begPos = 14 + InStrB(endPos + 1, value, stringToByte("Content-Type:"))
    endPos = InStrB(begPos, value, ChrB(13))

    midValue = MidB(value, begPos, endPos - begPos)
    intDict.Add "ContentType", trim(byteToString(midValue))

    begPos = endPos + 4
    endPos = LenB(value)

    nameValue = MidB(value, begPos, ((endPos - begPos) - 1))
    Else
    nameValue = trim(byteToString(MidB(value, nValue + 5)))
    End If

    If isValid = True Then

    intDict.Add "Value", nameValue
    intDict.Add "Name", nameN

    dict.Add byteToString(nameN), intDict
    End If
    End If

    currentPos = lenSeparator + inStrByte
    Wend
    End Sub

    End Class

    Private Function stringToByte(toConv)
    Dim tempChar
    For i = 1 to Len(toConv)
    tempChar = Mid(toConv, i, 1)
    stringToByte = stringToByte & chrB(AscB(tempChar))
    Next
    End Function

    Private Function byteToString(toConv)
    For i = 1 to LenB(toConv)
    byteToString = byteToString & Chr(AscB(MidB(toConv,i,1)))
    Next
    End Function
    %>

    On the next page we create other important files; insert.htm and insert.asp.




    Explanation
    Like before I will not be going into the details of Loader.asp coding, all the hard work has already been done and you should just use it. The only difference between this version of Loader.asp and previous versions is that it contains a new method saveToFile(name, path). This is the method we are going to use to save uploaded binary data to files on the server.



    Insert.htm
    Open your note pad and create a new text file save it as Insert.htm. Now copy the text listed below and paste it in to the newly created 'Insert.htm' page and hit the save button :


    <!-- insert.htm -->
    <html>
    <head>
    <title>File Uploading with ASP</title>
    <style>
    body, input { font-family:verdana,arial; font-size:10pt; }
    </style>
    </head>
    <body>
    <p align="center">
    <b>File Uploading with ASP</b><br>
    <a href="show.asp">To see uploaded data click here</a>
    </p>

    <table border="0" align="center">
    <tr>
    <form method="POST" enctype="multipart/form-data" action="Insert.asp">
    <td>Name :</td><td>
    <input type="text" name="name" size="40"></td></tr>
    <td>File :</td><td>
    <input type="file" name="file" size="40"></td></tr>
    <td> </td><td>
    <input type="submit" value="Submit"></td></tr>
    </form>
    </tr>
    </table>

    </body>
    </html>

    Insert.htm is going to be the HTML page which contains the Form we will be using to upload files.



    Insert.asp
    Open your note pad and create a new text file save it as Insert.htm. Now copy the text listed below and paste it in to the newly created 'Insert.asp' page and hit the save button :


    <% ' Insert.asp %>
    <!--#include file="Loader.asp"-->
    <%
    Response.Buffer = True

    ' load object
    Dim load
    Set load = new Loader

    ' calling initialize method
    load.initialize

    ' File binary data
    Dim fileData
    fileData = load.getFileData("file")
    ' File name
    Dim fileName
    fileName = LCase(load.getFileName("file"))
    ' File path
    Dim filePath
    filePath = load.getFilePath("file")
    ' File path complete
    Dim filePathComplete
    filePathComplete = load.getFilePathComplete("file")
    ' File size
    Dim fileSize
    fileSize = load.getFileSize("file")
    ' File size translated
    Dim fileSizeTranslated
    fileSizeTranslated = load.getFileSizeTranslated("file")
    ' Content Type
    Dim contentType
    contentType = load.getContentType("file")
    ' No. of Form elements
    Dim countElements
    countElements = load.Count
    ' Value of text input field "name"
    Dim nameInput
    nameInput = load.getValue("name")
    ' Path where file will be uploaded
    Dim pathToFile
    pathToFile = Server.mapPath("uploaded/") & "\" & fileName
    ' Uploading file data
    Dim fileUploaded
    fileUploaded = load.saveToFile ("file", pathToFile)

    ' destroying load object
    Set load = Nothing
    %>

    <html>
    <head>
    <title>File Uploading with ASP</title>
    <style>
    body, input, td { font-family:verdana,arial; font-size:10pt; }
    </style>
    </head>
    <body>
    <p align="center">
    <b>File Uploading with ASP</b><br>
    <a href="show.asp">To see uploaded files click here</a>
    </p>

    <table width="700" border="1" align="center">
    <tr>
    <td>File Name</td><td><%= fileName %></td>
    </tr><tr>
    <td>File Path</td><td><%= filePath %></td>
    </tr><tr>
    <td>File Path Complete</td><td><%= filePathComplete %></td>
    </tr><tr>
    <td>File Size</td><td><%= fileSize %></td>
    </tr><tr>
    <td>File Size Translated</td><td><%= fileSizeTranslated %></td>
    </tr><tr>
    <td>Content Type</td><td><%= contentType %></td>
    </tr><tr>
    <td>No. of Form Elements</td><td><%= countElements %></td>
    </tr><tr>
    <td>Name</td><td><%= nameInput %></td>
    </tr>
    </table><br><br>

    <p style="padding-left:220;">
    <%
    If fileUploaded = True Then
    Response.Write fileName & " data uploaded..."
    Else
    Response.Write "<font color=""red"">File could not be uploaded..."
    Response.Write "</font>"
    Response.Write "<br>Please select a file before hitting the 'Submit'"
    Response.Write " button."
    End If
    %>
    </p>

    <br>
    <table border="0" align="center">
    <tr>
    <form method="POST" enctype="multipart/form-data" action="Insert.asp">
    <td>Name :</td><td>
    <input type="text" name="name" size="40" value="<%= nameInput %>">
    </td></tr>
    <td>File :</td><td>
    <input type="file" name="file" size="40"></td></tr>
    <td> </td><td>
    <input type="submit" value="Submit"></td></tr>
    </form>
    </tr>
    </table>

    </body>
    </html>

    Insert.asp is the action page of the HTML Form present on Insert.htm page. It receives the binary data from the Form and parses it using the Loader class internally. You'll have to initialize the Loader class before using like this :


    Dim load
    Set load = new Loader
    load.initialize


    You can use it's different methods to get different values out of the Form.



    Explanation
    If you have been following my earlier articles then most of the code in Insert.asp will be familiar to you. So I'll explain only the changes :


    ' Path where file will be uploaded
    Dim pathToFile
    pathToFile = Server.mapPath("uploaded/") & "\" & fileName
    ' Uploading file data
    Dim fileUploaded
    fileUploaded = load.saveToFile ("file", pathToFile)

    ' destroying load object
    Set load = Nothing
    %>


    pathToFile variable is is set to the directory where we want to upload the file. Notice that fileName ( File Name ) is also appended at the end. Here we have set the path to a new folder named 'uploaded' which resides under the folder where Loader.asp, Insert.htm, Insert.asp and other files are present.



    Next we use the Loader.saveToFile function to save the binary data to the file. Notice that the first argument to the saveToFile method is name of the input tag you used in the 'Insert.htm' page and second argument is complete path to the directory along with the desired file name you want to give this to the new file. saveToFile returns a boolean value, True if file is uploaded and false if not.