Link to home
Start Free TrialLog in
Avatar of charles_cp
charles_cp

asked on

ASP upload script

Dear

I would like to upload a file to the web using ASP. I can’t install any program (e.g. ASPUpload) because I am rent a space of the web hosting.

I had tried the FreeASPUpload (http://www.freeaspupload.net/). It is work in upload file. Then, I tried to edit the script for add an input text box in the form. The upload function is work but I can’t use Request(“textboxname”) in the next page. It is empty in this variable. I think this is about the method=”POST” problem. If I change the method to GET. The variable information work but the upload function can’t.

Have any other ASP upload file script can do this? OR, anybody had tried add the input text box using FreeASPUpload and work? Please Help!

Thank You Very Much!

Charles
Avatar of kiddanger
kiddanger
Flag of United States of America image

Charles...

Request("textboxname") is not for forms using method="post".  It's when you don't know how the data will be sent.  If you use GET, then Request.QueryString("textboxname"), POST Request.Form("textboxname").

Show the form and the page it uploads to where you try to get the file and the textbox value.
Avatar of snavebelac
snavebelac

When you are using upload components like this the formsd enctype will be set to enctype="multipart/form-data".  in this case you will have to use the UploadedFiles.Form("") object  to retrieve any form data. The Request.Form("") object will not work.

FreeASPUpload quick Reference
Main class FreeASPUpload

Public properties:

UploadedFiles - A Dictionary of UploadedFile objects. You can check the length of keys to verify if the user actually uploaded any files; see example in the SaveFiles function of the uploadTester.asp code sample.

Files - Equivalent to: UploadedFiles.Items . The SaveFiles function in uploadTester.asp provides an example of how to loop over the Files array to get access to all file descriptions.

Form - A collection with the values of the form elements posted by the upload form. This collection is empty until the Save method is called.

HTH

C

Avatar of charles_cp

ASKER

I had tried the Request.Form("textboxname"). It's shows "Error ASP0206~Cannot call BinaryRead after using Request.Form collection "

The following is the FreeASPUpload script:
---uploadTester.asp---
<%@ Language=VBScript %>
<%
option explicit
Response.Expires = -1
Server.ScriptTimeout = 600
%>
<!-- #include file="freeaspupload.asp" -->
<%
  Dim uploadsDirVar
  uploadsDirVar = "C:\Inetpub\wwwroot\promotion\pro_temp"

function OutputForm()
%>
    <form name="frmSend" method="POST" enctype="multipart/form-data" action="uploadTester.asp" onSubmit="return onSubmitForm();">
    File 1: <input name=attach1 type=file size=35><br>
    File 2: <input name=attach2 type=file size=35><br>
    File 3: <input name=attach3 type=file size=35><br>
    File 4: <input name=attach4 type=file size=35><br>
    <br>
    <input style="margin-top:4" type=submit value="Upload">
    </form>
<%
end function

function TestEnvironment()
    Dim fso, fileName, testFile, streamTest
    TestEnvironment = ""
    Set fso = Server.CreateObject("Scripting.FileSystemObject")
    if not fso.FolderExists(uploadsDirVar) then
        TestEnvironment = "<B>Folder " & uploadsDirVar & " does not exist.</B><br>The value of your uploadsDirVar is incorrect. Open uploadTester.asp in an editor and change the value of uploadsDirVar to the pathname of a directory with write permissions."
        exit function
    end if
    fileName = uploadsDirVar & "\test.txt"
    on error resume next
    Set testFile = fso.CreateTextFile(fileName, true)
    If Err.Number<>0 then
        TestEnvironment = "<B>Folder " & uploadsDirVar & " does not have write permissions.</B><br>The value of your uploadsDirVar is incorrect. Open uploadTester.asp in an editor and change the value of uploadsDirVar to the pathname of a directory with write permissions."
        exit function
    end if
    Err.Clear
    testFile.Close
    fso.DeleteFile(fileName)
    If Err.Number<>0 then
        TestEnvironment = "<B>Folder " & uploadsDirVar & " does not have delete permissions</B>, although it does have write permissions.<br>Change the permissions for IUSR_<I>computername</I> on this folder."
        exit function
    end if
    Err.Clear
    Set streamTest = Server.CreateObject("ADODB.Stream")
    If Err.Number<>0 then
        TestEnvironment = "<B>The ADODB object <I>Stream</I> is not available in your server.</B><br>Check the Requirements page for information about upgrading your ADODB libraries."
        exit function
    end if
    Set streamTest = Nothing
end function

function SaveFiles
    Dim Upload, fileName, fileSize, ks, i, fileKey

    Set Upload = New FreeASPUpload
    Upload.Save(uploadsDirVar)

      ' If something fails inside the script, but the exception is handled
      If Err.Number<>0 then Exit function

    SaveFiles = ""
    ks = Upload.UploadedFiles.keys
    if (UBound(ks) <> -1) then
        SaveFiles = "<B>Files uploaded:</B> "
        for each fileKey in Upload.UploadedFiles.keys
            SaveFiles = SaveFiles & Upload.UploadedFiles(fileKey).FileName & " (" & Upload.UploadedFiles(fileKey).Length & "B) "
         next
    else
        SaveFiles = "The file name specified in the upload form does not correspond to a valid file in the system."
    end if
end function
%>

<HTML>
<HEAD>
<TITLE>Test Free ASP Upload</TITLE>
<style>
BODY {background-color: white;font-family:arial; font-size:12}
</style>
<script>
function onSubmitForm() {
    var formDOMObj = document.frmSend;
    if (formDOMObj.attach1.value == "" && formDOMObj.attach2.value == "" && formDOMObj.attach3.value == "" && formDOMObj.attach4.value == "" )
        alert("Please press the browse button and pick a file.")
    else
        return true;
    return false;
}
</script>

</HEAD>

<BODY>

<br><br>
<div style="border-bottom: #A91905 2px solid;font-size:16">Upload files to your server</div>
<%
Dim diagnostics
if Request.ServerVariables("REQUEST_METHOD") <> "POST" then
    diagnostics = TestEnvironment()
    if diagnostics<>"" then
        response.write "<div style=""margin-left:20; margin-top:30; margin-right:30; margin-bottom:30;"">"
        response.write diagnostics
        response.write "<p>After you correct this problem, reload the page."
        response.write "</div>"
    else
        response.write "<div style=""margin-left:150"">"
        OutputForm()
        response.write "</div>"
    end if
else
    response.write "<div style=""margin-left:150"">"
    OutputForm()
    response.write SaveFiles()
    response.write "<br><br></div>"
end if

%>

</BODY>
</HTML>




---FreeASPUpload.asp---
<%

Class FreeASPUpload
      Public UploadedFiles
      Public FormElements

      Private VarArrayBinRequest
      Private StreamRequest
      Private uploadedYet

      Private Sub Class_Initialize()
            Set UploadedFiles = Server.CreateObject("Scripting.Dictionary")
            Set FormElements = Server.CreateObject("Scripting.Dictionary")
            Set StreamRequest = Server.CreateObject("ADODB.Stream")
            StreamRequest.Type = 1 'adTypeBinary
            StreamRequest.Open
            uploadedYet = false
      End Sub
      
      Private Sub Class_Terminate()
            If IsObject(UploadedFiles) Then
                  UploadedFiles.RemoveAll()
                  Set UploadedFiles = Nothing
            End If
            If IsObject(FormElements) Then
                  FormElements.RemoveAll()
                  Set FormElements = Nothing
            End If
            StreamRequest.Close
            Set StreamRequest = Nothing
      End Sub

      Public Property Get Form(sIndex)
            Form = ""
            If FormElements.Exists(LCase(sIndex)) Then Form = FormElements.Item(LCase(sIndex))
      End Property

      Public Property Get Files()
            Files = UploadedFiles.Items
      End Property

      Public Sub Save(path)
            Dim streamFile, fileItem

            if Right(path, 1) <> "\" then path = path & "\"

            if not uploadedYet then Upload

            For Each fileItem In UploadedFiles.Items
                  Set streamFile = Server.CreateObject("ADODB.Stream")
                  streamFile.Type = 1
                  streamFile.Open
                  StreamRequest.Position=fileItem.Start
                  StreamRequest.CopyTo streamFile, fileItem.Length
                  streamFile.SaveToFile path & fileItem.FileName, 2
                  streamFile.close
                  Set streamFile = Nothing
                  fileItem.Path = path & fileItem.FileName
             Next
      End Sub

      Public Function SaveBinRequest(path) ' For debugging purposes
            StreamRequest.SaveToFile path & "\debugStream.bin", 2
      End Function

      Public Sub DumpData() 'only works if files are plain text
            Dim i, aKeys, f
            response.write "Form Items:<br>"
            aKeys = FormElements.Keys
            For i = 0 To FormElements.Count -1 ' Iterate the array
                  response.write aKeys(i) & " = " & FormElements.Item(aKeys(i)) & "<BR>"
            Next
            response.write "Uploaded Files:<br>"
            For Each f In UploadedFiles.Items
                  response.write "Name: " & f.FileName & "<br>"
                  response.write "Type: " & f.ContentType & "<br>"
                  response.write "Start: " & f.Start & "<br>"
                  response.write "Size: " & f.Length & "<br>"
             Next
         End Sub

      Private Sub Upload()
            Dim nCurPos, nDataBoundPos, nLastSepPos
            Dim nPosFile, nPosBound
            Dim sFieldName, osPathSep, auxStr
            Dim vDataSep
            Dim tNewLine, tDoubleQuotes, tTerm, tFilename, tName, tContentDisp, tContentType
            tNewLine = Byte2String(Chr(13))
            tDoubleQuotes = Byte2String(Chr(34))
            tTerm = Byte2String("--")
            tFilename = Byte2String("filename=""")
            tName = Byte2String("name=""")
            tContentDisp = Byte2String("Content-Disposition")
            tContentType = Byte2String("Content-Type:")

            uploadedYet = true

            on error resume next
            VarArrayBinRequest = Request.BinaryRead(Request.TotalBytes)
            if Err.Number <> 0 then
                  response.write "<br><br><B>System reported this error:</B><p>"
                  response.write Err.Description & "<p>"
                  response.write "The most likely cause for this error is the incorrect setup of AspMaxRequestEntityAllowed in IIS MetaBase. Please see instructions in the <A HREF='http://www.freeaspupload.net/freeaspupload/requirements.asp'>requirements page of freeaspupload.net</A>.<p>"
                  Exit Sub
            end if
            on error goto 0 'reset error handling

            nCurPos = FindToken(tNewLine,1) 'Note: nCurPos is 1-based (and so is InstrB, MidB, etc)

            If nCurPos <= 1  Then Exit Sub
             
            vDataSep = MidB(VarArrayBinRequest, 1, nCurPos-1)

            nDataBoundPos = 1

            nLastSepPos = FindToken(vDataSep & tTerm, 1)

            Do Until nDataBoundPos = nLastSepPos
                  
                  nCurPos = SkipToken(tContentDisp, nDataBoundPos)
                  nCurPos = SkipToken(tName, nCurPos)
                  sFieldName = ExtractField(tDoubleQuotes, nCurPos)

                  nPosFile = FindToken(tFilename, nCurPos)
                  nPosBound = FindToken(vDataSep, nCurPos)
                  
                  If nPosFile <> 0 And  nPosFile < nPosBound Then
                        Dim oUploadFile
                        Set oUploadFile = New UploadedFile
                        
                        nCurPos = SkipToken(tFilename, nCurPos)
                        auxStr = ExtractField(tDoubleQuotes, nCurPos)

                osPathSep = "\"
                if InStr(auxStr, osPathSep) = 0 then osPathSep = "/"
                        oUploadFile.FileName = Right(auxStr, Len(auxStr)-InStrRev(auxStr, osPathSep))

                        if (Len(oUploadFile.FileName) > 0) then 'File field not left empty
                              nCurPos = SkipToken(tContentType, nCurPos)
                              
                    auxStr = ExtractField(tNewLine, nCurPos)

                              oUploadFile.ContentType = Right(auxStr, Len(auxStr)-InStrRev(auxStr, " "))
                              nCurPos = FindToken(tNewLine, nCurPos) + 4 'skip empty line
                              
                              oUploadFile.Start = nCurPos-1
                              oUploadFile.Length = FindToken(vDataSep, nCurPos) - 2 - nCurPos
                              
                              If oUploadFile.Length > 0 Then UploadedFiles.Add LCase(sFieldName), oUploadFile
                        End If
                  Else
                        Dim nEndOfData
                        nCurPos = FindToken(tNewLine, nCurPos) + 4 'skip empty line
                        nEndOfData = FindToken(vDataSep, nCurPos) - 2
                        If Not FormElements.Exists(LCase(sFieldName)) Then FormElements.Add LCase(sFieldName), String2Byte(MidB(VarArrayBinRequest, nCurPos, nEndOfData-nCurPos))
                  End If

                  nDataBoundPos = FindToken(vDataSep, nCurPos)
            Loop
            StreamRequest.Write(VarArrayBinRequest)
      End Sub

      Private Function SkipToken(sToken, nStart)
            SkipToken = InstrB(nStart, VarArrayBinRequest, sToken)
            If SkipToken = 0 then
                  Response.write "Error in parsing uploaded binary request."
                  Response.End
            end if
            SkipToken = SkipToken + LenB(sToken)
      End Function

      Private Function FindToken(sToken, nStart)
            FindToken = InstrB(nStart, VarArrayBinRequest, sToken)
      End Function

      Private Function ExtractField(sToken, nStart)
            Dim nEnd
            nEnd = InstrB(nStart, VarArrayBinRequest, sToken)
            If nEnd = 0 then
                  Response.write "Error in parsing uploaded binary request."
                  Response.End
            end if
            ExtractField = String2Byte(MidB(VarArrayBinRequest, nStart, nEnd-nStart))
      End Function

      Private Function Byte2String(sString)
            Dim i
            For i = 1 to Len(sString)
               Byte2String = Byte2String & ChrB(AscB(Mid(sString,i,1)))
            Next
      End Function

      Private Function String2Byte(bsString)
            Dim i
            String2Byte =""
            For i = 1 to LenB(bsString)
               String2Byte = String2Byte & Chr(AscB(MidB(bsString,i,1)))
            Next
      End Function
End Class

Class UploadedFile
      Public ContentType
      Public Start
      Public Length
      Public Path
      Private nameOfFile

    Public Property Let FileName(fN)
        nameOfFile = fN
        nameOfFile = SubstNoReg(nameOfFile, "\", "_")
        nameOfFile = SubstNoReg(nameOfFile, "/", "_")
        nameOfFile = SubstNoReg(nameOfFile, ":", "_")
        nameOfFile = SubstNoReg(nameOfFile, "*", "_")
        nameOfFile = SubstNoReg(nameOfFile, "?", "_")
        nameOfFile = SubstNoReg(nameOfFile, """", "_")
        nameOfFile = SubstNoReg(nameOfFile, "<", "_")
        nameOfFile = SubstNoReg(nameOfFile, ">", "_")
        nameOfFile = SubstNoReg(nameOfFile, "|", "_")
    End Property

    Public Property Get FileName()
        FileName = nameOfFile
    End Property

End Class

Function SubstNoReg(initialStr, oldStr, newStr)
    Dim currentPos, oldStrPos, skip
    If IsNull(initialStr) Or Len(initialStr) = 0 Then
        SubstNoReg = ""
    ElseIf IsNull(oldStr) Or Len(oldStr) = 0 Then
        SubstNoReg = initialStr
    Else
        If IsNull(newStr) Then newStr = ""
        currentPos = 1
        oldStrPos = 0
        SubstNoReg = ""
        skip = Len(oldStr)
        Do While currentPos <= Len(initialStr)
            oldStrPos = InStr(currentPos, initialStr, oldStr)
            If oldStrPos = 0 Then
                SubstNoReg = SubstNoReg & Mid(initialStr, currentPos, Len(initialStr) - currentPos + 1)
                currentPos = Len(initialStr) + 1
            Else
                SubstNoReg = SubstNoReg & Mid(initialStr, currentPos, oldStrPos - currentPos) & newStr
                currentPos = oldStrPos + skip
            End If
        Loop
    End If
End Function
%>

---The OutputForm function which I edit ---
function OutputForm()
%>
    <form name="frmSend" method="POST" enctype="multipart/form-data" action="uploadTester.asp" onSubmit="return onSubmitForm();">
    File 1: <input name=attach1 type=file size=35><br>
    File 2: <input name=attach2 type=file size=35><br>
    File 3: <input name=attach3 type=file size=35><br>
    File 4: <input name=attach4 type=file size=35><br>
    Subject:<input name=subjecta type=text size=35><br>
    <br>
    <input style="margin-top:4" type=submit value="Upload">
    </form>
<%
Dim testsubject
testsubject = Request.Form("subjecta")
Response.Write testsubject
end function
See my post above, you cannot use Request.Form("textboxname") - it wont work because the enctype on the form.

C
Hello charles,

  From the code of the asp upload object posted above i can see that it has two useful methods
  that can do yur work.
 
   1. DumpData
   2. GetForm

  DumpData dumps information regarding the form elements and its values and also the file
  that was uploaded

 GetForm function can be used in place of Request.Form method to get the value of form elements.

  so instead of Request.Form("textboxname")
  do  Upload.Get Form("textboxname")

 
Dear C,

I had changed to the following code:

function OutputForm()
%>
    <form name="frmSend" method="POST" enctype="multipart/form-data" action="uploadTester.asp" onSubmit="return onSubmitForm();">
    File 1: <input name=attach1 type=file size=35><br>
    File 2: <input name=attach2 type=file size=35><br>
    File 3: <input name=attach3 type=file size=35><br>
    File 4: <input name=attach4 type=file size=35><br>
    Subject:<input name=subjecttest type=text size=30><br>
    <br>
    <input style="margin-top:4" type=submit value="Upload">
    </form>
<%
Dim aaa
aaa=UploadedFiles.Form("subjecttest")
response.write aaa
end function

-------------------------------------------

It gives me error message:

Error Type:
Microsoft VBScript runtime (0x800A01FA)
Class not defined: 'UploadedFiles'

Dear Vinod_VijayanVin,

I had tried using Upload.GetForm("subjecttest").

It gives me the error message also:

Error Type:
Microsoft VBScript runtime (0x800A01FA)
Class not defined: 'Upload'

Must using "DumpData" function? Have any example about this for reference?
Thank You very much!
uploadedFiles is a member funtion of the FreeASPUpload Class.

You will need to use

Upload.UploadedFiles.Form("subjecttest")

"Upload" is whatever you named your Upload object (Set Upload = New FreeASPUpload)

HTH

C

In  Upload.GetForm("subjecttest")

  The Upload is the object of type FreeASPUpload

 You may have declared somewhere

 Set [object name] = New FreeASPUpload
  here "object name" can be any name yu give to the object. In my previous post
 i considered Upload as the instance of FreeASPUpload like.

  Set Upload = New FreeASPUpload

 Whatever the name of the object is yu can use the method GetForm to get the form
 data like
   [object name].GetForm("subjecttest")

 e.g.
   Set Upload = New FreeASPUpload
   Upload.GetForm("subjecttest")

 Yu can use dumpData function to debug yur code. It prints all the
 names of files uploaded as also the form data.

 So to sum up do the following
 
 <%
  dim subject_test
   Set Upload = New FreeASPUpload
   subject_test = Upload.GetForm("subjecttest")              ' here subject_test gets the subjecttest  form data value
    Upload.DumpData()                                                  'print info of uploaded file(s)
%>









ASKER CERTIFIED SOLUTION
Avatar of Vinod_VijayanVin
Vinod_VijayanVin
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial