Solved

Count the number of files attached

Posted on 2006-07-18
4
287 Views
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
Upload.Save("\\opic-intranetdv\wwwroot$\angie\Attachments\")

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....
0
Comment
Question by:Gemini532
  • 2
  • 2
4 Comments
 
LVL 19

Expert Comment

by:nschafer
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,
Neal.
0
 

Author Comment

by:Gemini532
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_text.do                                                   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.

0
 

Author Comment

by:Gemini532
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">                  
</td></tr></table>
<%
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
Upload.Save("\\opic-intranetdv\wwwroot$\angie\Attachments\")

'****************DATABASE CONNECTION TO GET 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"
rs.open 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">
           window.close()
      </script>
      <%
end if
%>
</form>
0
 
LVL 19

Accepted Solution

by:
nschafer earned 500 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.

Neal.

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
<%@ 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
    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, rs, fs, v, fileExt, vFile, valid, vListingID, sql
  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
  ' 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") & "#,"
  else
    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 & ")"
  conn.execute(sql)
  set rs = conn.execute("Select @@Identity as ListingID")
  if not rs.eof then
    vListingID = rs("ListingID")
  else
    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)
        else
          '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  & "'"
          else
            sql = "Update tbListings set image" & v & "='" & vListingID & "_" & v & "." & FileExt  & "'"
          end if
          v = v + 1
        end if
      else
        ' Delete File
        fs.DeleteFile(uploadsDirVar & "\" & vFile)
      end if
       
       ' response.Write(Upload.UploadedFiles(fileKey).FileName & "," & Upload.UploadedFiles(fileKey).Length & ",")
    next
    if sql > "" then
      ' Update Database with Location to image files
      ' ----------------------------------------------------
      sql = sql & ",imagePath = '" & finalDirVar & "' where ListingID = " & vListingID
      conn.execute(sql)
    end if

  end if
 
 
end function
%>

<html>
<head>
<title>Upload Files</title>
</head>
<body>

<%
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."
   else
     response.write "<div style=""margin-left:150"">"
     response.write "</div>"
   end if
else
   ' Upload the Files
   SaveFiles()
   response.redirect("home.asp")
end if
%>
</body>
</html>
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

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…
Hello, all! I just recently started using Microsoft's IIS 7.5 within Windows 7, as I just downloaded and installed the 90 day trial of Windows 7. (Got to love Microsoft for allowing 90 days) The main reason for downloading and testing Windows 7 is t…
This video discusses moving either the default database or any database to a new volume.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

706 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now