Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


Count the number of files attached

Posted on 2006-07-18
Medium Priority
Last Modified: 2007-12-19
Hello Everyone, I'm trying to count the number of files that are attached and get that number in a variable called countFiles

Set Upload = New FreeASPUpload
Attachment = Upload.Form("attach1")
'Upload.OverwriteFiles = False   'makes sure the attachments have unique names, my code does that already by adding the ProposalId

dim nameofFile, countFiles
countFiles = 0
nameofFile = Upload.Form("attach1")

if (nameofFile <> "") then
      countFiles = countFiles + 1
end if

response.write countFiles

But this code doesn't work...
Can you help?  My idea is that each time the variable nameofFile has something in it, countFiles should get one added to it....
Question by:Gemini532
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
LVL 19

Expert Comment

ID: 17132288
Hi Gemini532,

I'm not really sure how this could work.  When you submit from the page with the form, there can only be one file in the attach1 field. so countFiles will either be 0 or 1.  It will reset to 0 on each upload, so I don't see the point.  

If you made it a session variable, then it could incremented.

Perhaps if you explained what you are trying to do with this count I could understand better how to assist you.

Since you are using FreeASPUpload another option you might want to think about is looking at the SaveFiles function.  This is the function that loops through the files to be uploaded and actually performs the upload.  You could add the counting code in the loop of this function.  That way if you were to have more than one upload field on the page it would keep the count correct.  

Hope this helps,

Author Comment

ID: 17132657
Wow!  That is great advice!  
I am trying to get the names of each files into the database and add the proposal id to it.
For example, if the user attaches  c://angie/text.doc            c://angie/cat.jpg          c://angie/MyCar.gif        and the proposalId   =150

In the Attachments table in the database it should be:
FileId                                   FileName                                            ProposalId
AutoNo                                                                         150
AutoNo                                150_cat.jpg                                                   150
AutoNo                                150_MyCar.gif                                               150

But I just don't know how to do it.  I think now that I know that the countFiles will be either 0 or 1, it explains why I just couldn't figure it out...
How do I create a session variable that contains all the FILES.  I did
Session("fileName") =  Upload.Form("file1")
But only THE LAST file would be saved, using the example above, only 150_MyCar.gif would be saved in the databse.


Author Comment

ID: 17132662
I will include my code in browse.asp

<FORM METHOD="POST"  ACTION="browse.asp" ENCTYPE="multipart/form-data" id = "mainform" name = "mainform" onSubmit = "saveFile()">
<table border="0" cellspacing="2" cellpadding="2" align="center"><tr><td>      
            Use the "Browse" button to find the files you would like to attach.<BR><br><br>      
                    <INPUT TYPE="FILE" NAME="attach1" VALUE="" size = "80">
                <INPUT TYPE="HIDDEN" NAME="file1"><br><br>                  
                  <input type = "submit" value = "Save and Attach Another" name = "attachBtn"  id = "attachBtn">
                  <INPUT TYPE="submit" value="Save and Close" name = "closeBtn" id = "closeBtn">                  
Set Upload = New FreeASPUpload
Attachment = Upload.Form("attach1")
'Upload.OverwriteFiles = False   'makes sure the attachments have unique names, my code does that already by adding the ProposalId

dim objConn
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.Open "Inv532","InvUser","InvPwd"
'******Open recordset to get the values from the Proposals table*****
dim rs, nextId

set rs = Server.CreateObject("ADODB.Recordset")
userRequestId = "Select TOP 1 [Proposals].[ProposalId] from [Proposals] order by DateSubmitted DESC" userRequestId, objConn

Dim fileArray( ) ' <<<< notice no size!
'ReDim fileArray(10) ' an arbitrary initial size

Session("fileName") = Upload.Form("file1")      
if not rs.eof then
      FilePath1 = Session("fileName")
      Set fs=Server.CreateObject("Scripting.FileSystemObject")    
      fileName = rs("ProposalId") & "_" & fs.GetFileName(FilePath1)
      set fs=nothing      

      'add each file name to the array
      ReDim Preserve fileArray( UBound(fileArray) + 1 )
    fileArray( UBound(fileArray) ) = fileName
      Session("fileName")  = fileArray
end if

if Upload.Form("closeBtn") <> "" then
      <script type="text/javascript">
end if
LVL 19

Accepted Solution

nschafer earned 2000 total points
ID: 17133200
>> How do I create a session variable that contains all the FILES.
OK, perhaps I need to define a session variable.  If you already know this information just ignore it I just want to make sure we are on the same page.  A session is created when a user connects to your site.  Session variables are used to store information and make it available from page to page within your site.  A common use for this is a UserID.  When a user logs into the site we set a session variable with the userID and then can verify on each page that the user is logged in and can use the ID for updating tables, etc...

It sounds more like you need to store this data to a table in a database.  I'm still not 100% sure where the counter comes into play.  But let me give you an example of a modified FreeASPUpload script that I use on one of my sites.  Perhaps this will help you.

In this modified version of the FreeASPupload script I am storing information about the files to a database.  I also have the files upload to an upload directory and then move to their final destination named appropriately.  Let me know if you have any trouble understanding this, or if you need help with anything else relating to this.


<%@ Language=VBScript %>
option explicit
Response.Expires = -1
Server.ScriptTimeout = 600
<!-- #include file="includes/dataopen.asp" -->  <!-- This include opens my data source and creates a connection -->
' ****************************************************
' Change the value of the variable below to the pathname
' of a directory with write permissions, for example "C:\Inetpub\wwwroot"
  Dim userID,uploadsDirVar, finalDirVar
' ****************************************************
userID = session("UserID")
uploadsDirVar = server.MapPath("/") & "\upload"
finalDirVar = server.MapPath("/") & "\attachments"
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
    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
    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, rs, fs, v, fileExt, vFile, valid, vListingID, sql
  Set Upload = New FreeASPUpload
      ' If something fails inside the script, but the exception is handled
  If Err.Number<>0 then Exit function
  ' Here we create the SQL to add the data to the table
  sql = "Insert into tbListings (CategoryID,UserID,DatePosted,DateToRemove,Subject,[When],Location,Contact,Description) values("
  sql = sql & upload.Form("subcat") & ","
  sql = sql & session("UserID") & ","
  sql = sql & "#" & now() & "#,"
  if isdate(upload.Form("expires")) then
    sql = sql & "#" & upload.Form("expires") & "#,"
    sql = sql & "#" & dateadd("m",1,now()) & "#,"
  end if
  sql = sql & "'" & upload.Form("Subject") & "',"
  sql = sql & "'" & upload.Form("When") & "',"
  sql = sql & "'" & upload.Form("Location") & "',"
  sql = sql & "'" & upload.Form("Contact") & "',"
  sql = sql & "'" & upload.Form("Description") & "'"
  sql = sql & ")"
  set rs = conn.execute("Select @@Identity as ListingID")
  if not rs.eof then
    vListingID = rs("ListingID")
    vListingID = 0
  end if
  sql = ""
  ks = Upload.UploadedFiles.keys
  set fs = server.CreateObject("Scripting.FileSystemObject")
  if (UBound(ks) <> -1) then
    v = 1
    for each fileKey in Upload.UploadedFiles.keys
      vFile = upload.UploadedFiles(fileKey).FileName
      ' Limit File Size to 128KB (Delete larger files)
      if upload.UploadedFiles(fileKey).Length < 128001 then
        ' Get the File Extension - Verify that it is an allowed Extension
        fileExt = right(vFile,len(vFile) - instrrev(vFile,"."))
        valid = 0
        select case fileExt
          case "jpg"
            valid = 1
          case "jpeg"
            valid = 1
          case "gif"
            valid = 1
          case "png"
            valid = 1
        end select
        if valid = 0 then  ' Invalid file extension (Delete File)
           fs.DeleteFile(uploadsDirVar & "\" & vFile)
          'Move file to Attachments Folder with new name
          fs.MoveFile uploadsDirVar & "\" & Upload.UploadedFiles(fileKey).FileName, finalDirVar & "\" & vListingID & "_" & v & "." & FileExt
          ' update SQL Statement
          ' -----------------------------------
          if left(sql,1) = "U" then
            sql = sql & ",image" & v & "='" & vListingID & "_" & v & "." & FileExt  & "'"
            sql = "Update tbListings set image" & v & "='" & vListingID & "_" & v & "." & FileExt  & "'"
          end if
          v = v + 1
        end if
        ' Delete File
        fs.DeleteFile(uploadsDirVar & "\" & vFile)
      end if
       ' response.Write(Upload.UploadedFiles(fileKey).FileName & "," & Upload.UploadedFiles(fileKey).Length & ",")
    if sql > "" then
      ' Update Database with Location to image files
      ' ----------------------------------------------------
      sql = sql & ",imagePath = '" & finalDirVar & "' where ListingID = " & vListingID
    end if

  end if
end function

<title>Upload Files</title>

Dim diagnostics
if Request.ServerVariables("REQUEST_METHOD") <> "POST" then
   diagnostics = TestEnvironment()
   if diagnostics<>"" then
     response.write "<br />After you correct this problem, reload the page."
     response.write "<div style=""margin-left:150"">"
     response.write "</div>"
   end if
   ' Upload the Files
end if

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I recently decide that I needed a way to make my pages scream on the net.   While searching around how I can accomplish this I stumbled across a great article that stated "minimize the server requests." I got to thinking, hey, I use more than one…
I was asked about the differences between classic ASP and ASP.NET, so let me put them down here, for reference: Let's make the introductions... Classic ASP was launched by Microsoft in 1998 and dynamically generate web pages upon user interact…
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …

688 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question