Solved

save the file name of several attachments

Posted on 2006-07-17
13
540 Views
Last Modified: 2012-06-27
Hello Everyone,
My application is supposed to save the name for each attached file, but it only saves the LAST one...         :(
In other words, even if the user attaches 3 files to the form, for example:
text.htm, doc.asp and cat.jpg, and the proposalId is 150, it shows 150_cat.jpg ONLY <--------the last file
It does not save any of the other files.

The code is done in 2 separate files.  First file is called "browse.asp"  This is where the user chooses his attachments (which are saved to a folder on the webserver).

The second file is "proposals.asp" this is where I use FSO to get the file name of each proposal and save it to the database after adding the ProposalId to it...  That way each file is unique and I'll know who sent the file based on the proposalId...

The code that does NOT work is in PROPOSALS.asp    I need it to save ALL the fileNames for each attachment, not just the last one.  Can you help?


'***************************************Code for browse.asp***************************

<FORM METHOD="POST"  ACTION="browse.asp" ENCTYPE="multipart/form-data" 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 Close" name = "closeBtn" id = "closeBtn">
      <input type = "submit" value = "Save and Attach Another" name = "attachBtn"  id = "attachBtn"><br></td> </tr></table>

<%
Set Upload = New FreeASPUpload
Attachment = Upload.Form("attach1")
Upload.Save("\\fake \fake\")

dim objConn, rs, nextId
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.Open "fake"," fake"," fake"
      
set rs = Server.CreateObject("ADODB.Recordset")
userRequestId = "Select TOP 1 [Proposals].[ProposalId] from [Proposals] order by DateSubmitted DESC"
rs.open userRequestId, objConn

Session("fileName") =  Upload.Form("file1")

'Close the “Save and Close” button after it saves the file
if Upload.Form("closeBtn") <> "" then
%>
<script type="text/javascript">      
     window.close()
</script>
<%
end if
%>
<SCRIPT language="JavaScript">
function saveFile(){
      document.mainform.file1.value = document.mainform.attach1.value;
      //alert(document.mainform.file1.value);
}
</SCRIPT>
</form>


'***************************************Code for proposals.asp**************************

'Open recordset to get the "ProposalId" from the "Proposals" table
dim rs
set rs = Server.CreateObject("ADODB.Recordset")
userRequestId = "Select Top 1 [Proposals].[ProposalId] from [Proposals] where [Proposals].[FirstName] = ('" & singleQuoteReplace(fName) & "') and [Proposals].[LastName] = ('" & singleQuoteReplace(lName) & "') and [Proposals].[ZipCode] = ('" & singleQuoteReplace(ZipCode) & "') order by DateSubmitted DESC"
rs.open userRequestId, objConn

if not rs.eof then
      FilePath1 = Session("fileName")
      Set fs=Server.CreateObject("Scripting.FileSystemObject")    
                  
      fileName1 = rs("ProposalId") & "_" & fs.GetFileName(FilePath1)
      response.write("<br>" & fileName1 & "<br>")
      set fs=nothing
end if

if fileName1 <> "" then
      attachmentsSQL = "INSERT into [Attachments] (FileName, ProposalId) values ('" & fileName1 & "', '" & rs("ProposalId") & "')"
      objConn.Execute attachmentsSQL
end if
0
Comment
Question by:Gemini532
  • 6
  • 3
  • 2
  • +1
13 Comments
 
LVL 1

Expert Comment

by:hangar18
ID: 17124420
This seems to be pretty obvious because I dont see anywhere where you are looping through the list of uploaded files. Or am i missing something here?

One workaround is to have an array of filenames in the Session("fileName") or you can look at  having a class with 2 properties and have a collection of these objects in Session.

Array might be a better solution.


0
 

Author Comment

by:Gemini532
ID: 17124493
can you help me code it?
0
 

Author Comment

by:Gemini532
ID: 17124508
array would be better because I need the file names in variables, so I can then add them to the database....
But I don't know how to code it...
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 17126002
Gemini532,

The steps to create the array will depend on what the string is like.  If you don't know then use a Response.Write on the proposals.asp page to see what is in the field.

The easiest is to use a function.  If the information is in a string and has a common delimiter, like a comma, then you can easily create a single dimension array filled with the info using Split.  For example ...

   myArray = Split(Session("fileName"), ",")

Let me know if you have any questions.  If you would like more information or a different example then it would help to find out what the string looks like.

b0lsc0tt
0
 

Author Comment

by:Gemini532
ID: 17130624
the fileName is made up of the path of the document attached by the user
For example:

c://angie/text.doc

or

d://mydocuments/mypictures/myKitty.jpg
0
 

Author Comment

by:Gemini532
ID: 17131380
THis is my code, but it does'nt work
Dim myArray()
Dim i

myArray = Session("fileName")
i = Ubound(myArray)+1
Redim Preserve myArray(i)

myArray(i) = Upload.Form("file1")
Session("fileName") = myArray()

But if I do this:   myArray = Session("fileName")
I get Type mismatch
and if I do this  myArray() = Session("fileName")
I get script out of range error
0
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

 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 17131868
What is in Session("fileName")?  What does it look like if it contains more than one file name?  With that information we should be able to help you correct the problem.

If you want to find out what is in Session("fileName") then use the 2 lines below.  Insert them right above the line "myArray = Session("fileName")."  You may need to comment out the myArray line.  I included that in my example below.

   Response.Write "fileName is " & Session("fileName")
   Response.End
   ' myArray = Session("fileName")

Let me know if you have any questions.
0
 
LVL 16

Expert Comment

by:ThinkPaper
ID: 17132209
I'm confused as to why you would need to use session variables to store the filenames..
I think I did something similar to what you are describing..

This is the way I did it:

form.asp
===========
//user inputs all register info
//if user clicks "submit & attach files", form is submitted to DB, and upload.asp pops up as pop up window.
//if user clicks only "submit", form is submitted to DB

<% If Request("Submit") <> "" Then

'do your query to INSERT table stuff

  If Request("Submit") ="Attach Files" Then

    'call pop up window upload.asp
  Else

  ' go to thankyou page
  End If

End If
%>

<form method="post" action="">
Name: <input type="text" name="Name" value = "">
Job: <input type="text" name="Job" value = "">
Phone: <input type="text" name="Phone" value = "">
<input type="Submit" name = "Submit"> <input type="Submit" name = "Submit" value = "Attach Files">
</form>


upload.asp looks something like:
============
<form method="post" action="file_toFileSystem.asp?id=<%=varID%>" enctype="multipart/form-data">
            1. <input type="file" name="FILE1" size="61"><br>
            2. <input type="file" name="FILE2" size="61"><br>
            3. <input type="file" name="FILE3" size="61"><br>
            4. <input type="file" name="FILE4" size="61"><br>
            5. <input type="file" name="FILE5" size="61">
<input type="submit" value="Attach Files" name="Upload" >

So then user is allowed 5 simultaneous file uploads at once. If you need more than 5, you can use javascript to make a drop down to display more fields. . Once they pick all files and click "Upload"
it goes to file_toFileSystem.asp

file_toFileSystem.asp looked something like:
==============
<%
' Instantiate Upload Class
Set objUpload = New clsUpload

Dim queryUpload

  For p = 1 to 5    'notice using for loop to loop thru the 5 fields

      ' Grab the file name
      strFileName = Trim(objUpload.Fields("File"&p).FileName)
                        
      If strFileName <> "" Then  'if field is not blank
      '--- UPLOAD FILE ---
      strFileName = Replace(strFileName, ".", "_"&myTimeStamp&".")
                 '-- Automatically insert timestamps to filename for unique filenames
                  
            ' Compile path to save file to
            strPath = Server.MapPath("myFolder") & "\" & strFileName      
            
            ' Save the binary data to the file system
            objUpload("File"&p).SaveAs strPath
                  
            '--- file has been saved in folder, so now to store file URL in the Database... -----
      '--- INSERT FILE INFO TO TABLE (DATABASE)---
      queryUpload = " INSERT INTO tbl_Register_Files "&_
                                     " (ID, FileURL, DateUploaded, AuthorID) Values " &_
              " ('"&ID&"', 'myfolder/"& strFileName & "', '"&Now()&"', '"&Session("username")&"');"
            
      objConn.Execute queryUpload

                  
   End If
      
 Next

' Release upload object from memory
Set objUpload = Nothing

set fs=nothing

%>
0
 

Author Comment

by:Gemini532
ID: 17132348
I don't know how many attachments the user will choose, that's the whole problem of my code...   :(
0
 

Author Comment

by:Gemini532
ID: 17132593
I think the problem is that I just cannot figure out how to find out how many attachments the user chose and do a for loop such as

for i = 1 to CountFiles
next

I took 's advice and I did, in proposals.asp:
Response.Write "fileName is " & Session("fileName")
   Response.End

I get this error:
Microsoft VBScript runtime error '800a000d'

Type mismatch

/angie/Proposals.asp, line 134



This is my code in Browse.asp, the idea is to add the name of the files that are attached into an array, and then I can put this array in a session variable which I can call from proposals.asp so I can put each file name into the database, but it's not working     :(


<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 54

Expert Comment

by:b0lsc0tt
ID: 17132699
Add a line above the code I provided like the one below.  You may comment out the Response.Write line that is trying to print Session("fileName") if it is the line with the error.

   Response.Write "fileName type is " & vartype(Session("fileName")) & "<br>"

What is line 134?  It seems like it may be a line that is causing an error but not one of the lines I provided.  If so, then temporarily comment it out by adding a single quote mark to the beginning of the line.  Review the code because you may also have to comment out other lines that are creating an error or will be affected by a line you temporarily comment out.

The lines I provided should not have caused a type mismatch error.  The information I provided above will test that though.  By the way, you may not need to get the count of the files to create an array.  We do need to find out what is in the variable that holds the file name(s).
0
 
LVL 16

Accepted Solution

by:
ThinkPaper earned 500 total points
ID: 17138689
>>"I think the problem is that I just cannot figure out how to find out how many attachments the user chose and do a for loop such as

for i = 1 to CountFiles
next"
---
you can still consider providing the user with a max number of fields for file attachments (say 20). user doesn't have to upload 20, but they have the option to.

set CountFiles = 20

so for:

for i = 1 to CountFiles
if filename(i) <> "" Then
 //do your upload
else
//its empty do nothing
end if

next

but if you plan on sticking to your version.. do what bolscott suggests and see why you're getting an type mismatch...

does your Session("fileName") look something like:
dog.jpg,cat.jpg,bird.jpg or something else?

And how are you storing the filename in Session("fileName") ?
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

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…
I would like to start this tip/trick by saying Thank You, to all who said that this could not be done, as it forced me to make sure that it could be accomplished. :) To start, I want to make sure everyone understands the importance of utilizing p…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

746 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

12 Experts available now in Live!

Get 1:1 Help Now