How to display four images with rotate effect from folder using classic ASP? - asp-classic

I have one folder in which my images get stored, now I want to create a slideshow such as the one here.
I tried the following code (but it displays just single image on page refresh):
<%#LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<html>
<head>
<%
Function RandomImage(strPath,strDefault)
On Error Resume Next
'response.Write("HI")
Randomize Timer
' declare all variables
Dim objFSO, objFolder, objFiles, objFile
Dim strFiles, strImages, strPhysical, strFile
' this constant has the names of valid image file name
' extensions and can be modified for more image types
Const strValid = ".gif.jpg.png"
' make sure we have a trailing slash in the path
If Right(strPath,1) <> Chr(47) Then strPath = strPath & Chr(47)
' get the physical path of the folder
strPhysical = Server.MapPath(strPath)
' get a File System Object
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
' create a folder object
Set objFolder = objFSO.GetFolder(strPhysical)
' get the files collection
Set objFiles = objFolder.Files
' enumerate the files collection looking for images
For Each objFile in objFiles
strFile = LCase(objFile.Name)
If Instr(strValid,Right(strFile,4)) Then
' add vaild images to a string of image names
strFiles = strFiles & strFile & vbTab
End If
Next
' split the image names into an array
strImages = Split(strFiles,vbTab)
' if we have an array...
If UBound(strImages) > 1 Then
' get a random name
RandomImage = strPath & strImages(Int(Rnd(1)*UBound(strImages)))
Else
' otherwise return the default
RandomImage = strDefault
End If
End Function
%>
<%
strImg = RandomImage("./retailers/","./retailers/A1-Supplements.jpg")
strsplit = split(strImg,"/")
' Response.Write(strsplit(2))
' Response.Write("rahul =" &strImg)
' d_desc = Split(Request.Form("strImg"),"/")
' Name of text file to search:
strFileName = "saveimagename.txt"
' Text to search for:
strSearchText = strsplit(2)
'response.Write(strSearchText)&"<br/>"
'response.end()
' Create an instance of the the File System Object
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
' Open the file
Set objTextFile = objFSO.OpenTextFile(Server.MapPath(strFileName))
URLString = ""
Do While Not objTextFile.AtEndOfStream
strReadLineText = objTextFile.ReadLine
'response.Write(strReadLineText & "<br>")
If strReadLineText<>"" then
If Instr(strReadLineText,",")>0 then
strReadLineTextArr=split(strReadLineText,",")
URLString=strReadLineTextArr(1)
end if
end if
If InStr(lcase(strReadLineText), lcase(strSearchText)) > 0 Then
Exit Do
End If
Loop
strSearchText=""
' Close and release file references
objTextFile.Close
Set objTextFile = Nothing
Set objFSO = Nothing
'Response.Write URLString
'Response.End()
%>
</head>
<body>
<div align="center" style="width:800px; float:left;">
<center>
<table border="0" width="800px">
<tr>
<td>
</td>
<td bgcolor="#000" align="center" style="border:none;">
<img src="<%=strImg%>" onClick="<%=URLString%>" border="0">
</td>
<td>
</td>
</tr>
</table>
</center>
</div>
</body>
</html>
Please help me.

Try to accomplish this from the server-side is very difficult. You can only assign the images once and the only way to change them is for your user to refresh the page.
What you need to do is create your slideshow on the client-side with JavaScript. Fortunately, there are lots of libraries that can help you. Search for slideshows and jquery and you should be able to find what you need. Here's one such link.

You definitely want to do this on the client side using jQuery. It will be more efficient for your end users and less server interaction.
Here are a few good slideshows with tutorials on how to implement them:
http://speckyboy.com/2009/06/03/15-amazing-jquery-image-galleryslideshow-plugins-and-tutorials/

Related

Getting value of field from form - VBscript

I have just downloaded a .net image uploader from github, it works a treat but because it's still got all the settings it came with, each image that's being uploaded is being named the same, and as such each image is overwriting the last.
When this is live, I would like the images to be named by the title and artist of the individual item.
I don't have much experience with .net, normally with asp I would request("fieldname") and carry that across, but this doesn't work
So my question is, how do I take the value of the field "thisuser" from the form and append the "upload_original" and "upload_thumb" variables in the code above?
I tried dim thisuser as integer, and a few other things but kept getting errors as I am unfamiliar with .net.
Code below:
<SCRIPT LANGUAGE="VBScript" runat="server">
const Lx = 200 ' max width for thumbnails
const Ly = 240 ' max height for thumbnails
const upload_dir = "upload_resize_test/" ' directory to upload file
const upload_original = "sample" ' filename to save original as (suffix added by script)
const upload_thumb = "thumb" ' filename to save thumbnail as (suffix added by script)
const upload_max_size = 2000 ' max size of the upload (KB) note: this doesn't override any server upload limits
dim fileExt ' used to store the file extension (saves finding it mulitple times)
dim newWidth, newHeight as integer ' new width/height for the thumbnail
dim l2 ' temp variable used when calculating new size
dim fileFld as HTTPPostedFile ' used to grab the file upload from the form
Dim originalimg As System.Drawing.Image ' used to hold the original image
dim msg ' display results
dim upload_ok as boolean ' did the upload work ?
</script>
And the form that it comes from with the field and its value I want to append to the file name (upload_original and upload_thumb_
<form enctype="multipart/form-data" method="post" runat="server">
<table>
<tr><td>Select the file to upload:</td><td><input name="thisuser" id="thisuser" type="hidden" value="123"><input type="file" name="upload_file"></td></tr>
<tr><td colspan=2>Max upload size <%=upload_max_size%>Kb, gif/jpg/png only</td></tr>
<tr><td colspan=2><input type="submit" value="Upload"></td></tr>
</table>
</form>
Naturally there is more code but I don't think it's relevant and don't want to clog up the post!
Many thanks
Request.Form("FieldName") is used to get the values of the form fields.

ASP Classsic - Insert into Excel .XLS columns or Create a Real Excel Format File

I would like to add my MS SQL data into the Excel .XLS file below.
I tried the following:
<%
Response.Clear
Response.Buffer = False
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader "Content-Disposition", "attachment;filename=example.xls"
' --OPEN MS SQL DATABASE CODE--
' --OPEN RECORDSET CODE--
%>
<table>
<tr>
<th>DEBNAME</th>
<th>INV_ID</th>
<th>INV_DATE</th>
<th>PO_NO</th>
<th>INVAMT</th>
</tr>
<% 'START OF: ROW LOOP
Do Until objRS.EOF
%>
<tr>
<td><%=objRS("DEBNAME")%></td>
<td><%=objRS("INV_ID")%></td>
<td><%=objRS("INV_DATE")%></td>
<td><%=objRS("PO_NO")%></td>
<td><%=objRS("INVAMT")%></td>
</tr>
<%
objRS.MoveNext
Loop
objRS.Close
'END OF: ROW LOOP
%>
</table>
THEN WHEN I TRY TO OPEN IT, IT GIVES ME THIS ERROR:
I think this is because the file only has HTML code inside it (I opened it via Notepad to check it out)
If I click on Yes the data will show but I would like to generate a real .xls file or use an empty.xls file, clone it, and then insert the data into it.
THANKS FOR ANY HELP!
This is how my empty.xls file looks
Using an empty file that ready to fill is the most painless method.
After filling the sheet(s) via related data providers, you can serve the static excel file or stream it.
Here's the demo : http://aspfiddle.com/ymuikl0id4/test.asp (will be deleted a few days later)
Make sure that you have permission to create new files.
Hope it helps.
<%#Language=VBScript CodePage=65001%>
<%
If Request.Form.Count Then 'form handling
Dim Fso
Set Fso = Server.CreateObject("Scripting.FileSystemObject")
Dim emptyXlsFileName
emptyXlsFileName = Server.Mappath("test.xls") 'empty original file path
Dim filledXlsFileName
filledXlsFileName = Replace(Fso.GetTempName, ".tmp", ".xls") 'temp file will be created and filled
Fso.CopyFile emptyXlsFileName, Server.Mappath(filledXlsFileName)
Dim Connection
Set Connection = Server.CreateObject("Adodb.Connection")
Connection.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.Mappath(filledXlsFileName) & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=0"";"
'Since Jet.OLEDB.4.0 is a 32-Bit only provider
'if you need to run this application in a 64-bit environment
'you have to install 64-bit version of Access Database Engine (http://www.microsoft.com/en-us/download/details.aspx?id=13255) to the server
'then use the following connection string instead
'Connection.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Server.Mappath(filledXlsFileName) & ";Extended Properties=""Excel 8.0;HDR=YES;IMEX=0"";"
Dim Recordset
Set Recordset = Server.CreateObject("Adodb.Recordset")
Recordset.Open "[Sheet1$]", Connection, , 3
Recordset.Addnew
Recordset("DEBNAME").Value = Request.Form("DEBNAME")
Recordset("INV_ID").Value = Request.Form("INV_ID")
Recordset("INV_DATE").Value = Request.Form("INV_DATE")
Recordset("PO_NO").Value = Request.Form("PO_NO")
Recordset("INVAMT").Value = Request.Form("INVAMT")
Recordset.Update
Recordset.Close
Set Recordset = Nothing
Connection.Close
Set Connection = Nothing
Const BufferSize = 8192
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader "Content-Disposition", "attachment;filename=example.xls"
Dim Stm
Set Stm = Server.CreateObject("Adodb.Stream")
Stm.Type = 1 'adTypeBinary
Stm.Open
Stm.LoadFromFile Server.Mappath(filledXlsFileName)
Do While Not Stm.EOS
Response.BinaryWrite Stm.Read(BufferSize)
Response.Flush
If Not Response.IsClientConnected Then Exit Do
Loop
Stm.Close
Set Stm = Nothing
Fso.DeleteFile Server.Mappath(filledXlsFileName)
Response.End
Set Fso = Nothing
End If
%><!doctype html>
<html lang="en">
<head>
<title>Insert Into Excel File</title>
<meta charset="utf-8">
</head>
<body>
<form method="post" target="_blank">
<table>
<tr><td>DEBNAME</td><td><input type="text" name="DEBNAME" value="John Doe" /></td></tr>
<tr><td>INV_ID</td><td><input type="text" name="INV_ID" value="123" /></td></tr>
<tr><td>INV_DATE</td><td><input type="text" name="INV_DATE" value="24 Jun, 2014" /></td></tr>
<tr><td>PO_NO</td><td><input type="text" name="PO_NO" value="321" /></td></tr>
<tr><td>INVAMT</td><td><input type="text" name="INVAMT" value="etc" /></td></tr>
<tr><td> </td><td><input type="submit" value="Add & Download" /></td></tr>
</table>
</form>
</body>
</html>
This will only be a partial/hack answer, because for everything from Excel 2007 on, I don't know that you can bypass that warning (unless you use a third-party library, and I don't know of any for ASP classic -- plenty of choices for ASP.NET). Here is a MS article on this subject, and it leads to the hack:
http://blogs.msdn.com/b/vsofficedeveloper/archive/2008/03/11/excel-2007-extension-warning.aspx
What you can do is alter your code slightly and deliver the data in CSV format. This will still download and open directly in Excel, but you won't get the warning. So here's the guts of it:
<%
Response.Clear
Response.Buffer = False
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader "Content-Disposition", "attachment;filename=example.csv"
Response.Write "DEBNAME, INV_ID, INV_DATE, PO_NO, INVAMT" & vbCRLF
Do Until objRS.EOF
Response.Write objRS("DEBNAME") & ", " & objRS("INV_ID") & ", " & objRS("INV_DATE") & ", " & objRS("PO_NO") & ", " & objRS("INVAMT") & vbCRLF
objRS.MoveNext
Loop
objRS.Close
%>

displaying images from sql database with classic asp

i am creating a home page and have a news section. currently the news section displays the top 3 news titles/headlines from the database they are stored in. How the owner wants it now is that an image should be displayed next to the news headline relating to that news article. So i have set up a function where by they upload an image into the news database against the article they have just created/uploaded into the database, now all i want to do is display this image that is saved in the database. Is there a way to do this?
i am using classic asp and html/javascript.
so far the code i have is:
<img id="news_image2" alt="<%=rsNews("Image_Name")%>" border="0" height="70" name="Image" src="<%=rsNews("news_Image")%>" title="Echo_Images" width="80" align="middle" /> </a>
Many thanks
EDIT. tHE IS THE rsnews on homepage.asp
<%# language="VBSCRIPT" codepage="1252" %>
<!-- #include file="Connections/echo.asp" -->
<%
Dim rsNews
Dim rsNews_numRows
Set rsNews = Server.CreateObject("ADODB.Recordset")
rsNews.ActiveConnection = MM_echo_STRING
rsNews.Source = "SELECT top 3 News_Article_ID,News_Article_Create_Date,News_Txt_Date,News_Title,News_Publish_Date,News_Expiry_Date,News_Title_Header,News_Active,Admin_ID,News_Ticker,display,Image_Name,displayCode,news_Image FROM tblNews WHERE News_Active = 1 AND News_Expiry_Date >= getDate() AND (display = 'ext' OR display = 'both'OR displayCode=1 OR displayCode=4 OR displayCode=5 OR displayCode=7) ORDER BY News_TXT_Date DESC"
rsNews.CursorType = 0
rsNews.CursorLocation = 2
rsNews.LockType = 1
rsNews.Open()
rsNews_numRows = 0
%>
<div id="news-home-container">
<!--news item 1-->
<div>
<div class="news-home-image">
<a href="about/echo_news.aspx?id=0">
<img id="news_image2" alt="LatestNews" border="0" height="70" name="logo_link0" src="image_display.asp?PhotoID=627" title="Echo_Images" width="80" align="middle" /></a> </div>
<div class="newsDiv">
<a href="about/echo_news.aspx?id=0" ><b style="line-height:1.3em"><%=rsNews("News_Title")%></b>
<p><%=rsNews("News_Title_Header")%></p></a>
</div>
</div>
<!--End of news item 1-->
now i need the images that are saved to the top 3 articles in the database to be displayed .
this is the code in image_display.asp
<!-- #include file="Connections/echo.asp" -->
<%
Dim sql
Dim rs
Dim conn
Dim userID,str
userID = Request("PhotoId")
If userID = "" Then userID = 0
'Instantiate Objects
Set conn = Server.CreateObject("ADODB.Connection")
Set rs = Server.CreateObject("ADODB.Recordset")
'Open connection
' rsNews.ActiveConnection = MM_echo_STRING
'conn = uncomment this line and insert your connection string here
'Get the specific image based on the ID passed in a querystring
str = "SELECT news_Image FROM tblNews WHERE news_article_id =" & userID
rs.Open str, conn,3,3
if rs.eof then 'No records found
Response.End
else 'Display the contents
Response.ContentType = "image/gif"
Response.BinaryWrite(rs("news_Image"))
end if
'destroy the variables.
rs.Close
conn.Close
set rs = Nothing
set conn = Nothing
%>
i figured it out. the issue was that the image was not been loaded into the database correctly so i recreated the page where the image was loaded and then used Jatins code above, only altering the "ID" to "News_Article_ID". once this was done i entered the following code into the img source
img src="Image_Display.asp?news_Article_iD=<%=rsnews("News_article_id")%>"
many thaks for your help everyone
heavencore's answer is right
you just need to check if you are binary writing hte right thing
so check if you are passing the right id onto the page and then where it says response.binarywrite rs("ImageBlob") - imageblob is the field where you saved your image as binary data
Edit after seeing your comment:
I have just had a look in your source code -
you where this line of code is
<img id="news_image2" alt="LatestNews" border="0" height="70" name="logo_link0" src="images/News_images/default image.jpg" title="Echo_Images" width="80" align="middle" />
You need to replace it with -
<img id="news_image2" alt="LatestNews" border="0" height="70" name="logo_link0" src="somefile.asp?ID=2" title="Echo_Images" width="80" align="middle" />
so you just change the src="" to src="somefile.asp?id=2"
and then in somefile.asp you put this code -
Dim ImageID
ImageID = request.querystring("ID")
Set rs = db.Execute("SELECT ImageBlob FROM table WHERE ID = " & ImageID)
Response.Expires = 0
Response.Buffer = TRUE
Response.Clear
Response.ContentType = "image/jpeg" '#### Assuming your images are jpegs
Response.BinaryWrite rs("ImageBlob")
Does this help?
Ok, based on your comments you'll need to create a new asp page, lets call it getImage.asp.
You would reference the image in your HTML as follows:
<img src="getImage.asp?ID=<%=rsNews("Image_ID") %>">
where getImage.asp is something like this (note the use of response.BinaryWrite:
Dim ImageID
ImageID = request.querystring("ID")
Set rs = db.Execute("SELECT ImageBlob FROM table WHERE ID = " & ImageID)
Response.Expires = 0
Response.Buffer = TRUE
Response.Clear
Response.ContentType = "image/jpeg" '#### Assuming your images are jpegs
Response.BinaryWrite rs("ImageBlob")

I would like to get this code to upload pictures to 2 different folders

We are trying to use persits upload code to upload pictures to 2 different folders. It works when uploading to just one folder but not 2 folders.
Essentially, we have two folders, one is called img and the other is a subdirectory of img called small.
We grab 1 picture and upload same picture into both img and small folders.
So far, the picture gets uploaded to small folder but not to img folder.
Below is the relevant code followed by a link where I got my sample code from.
'Upload.asp
<form name="form" action="process.asp" method="post" ENCTYPE="multipart/form-data">
<Table>
<tr>
<td class="body1" div align="right">Attach for IMG folder:</div></td>
<td><INPUT NAME="file1" TYPE="FILE" value="" SIZE=30></td>
</tr>
<tr>
<td class="body1" div align="right">Attach for SMALL folder:</div></td>
<td><INPUT NAME="file2" TYPE="FILE" value="" SIZE=30></td>
</tr>
</table>
</td>
</tr>
</table>
<hr color="silver">
<table width="100%" border="0" cellspacing="4" cellpadding="4">
<tr>
<td><div align="center">
<input type="image" name="submit" id="submit2" title="submit to db." border="0" src="images/submitbutton.jpg" width="142" height="47" alt="Submit Button">
</div></td>
</tr>
</table>
</form>
'Process.asp
<%
Set Upload = Server.CreateObject("Persits.Upload")
' Limit file size to 5000000 bytes, throw an exception if file is larger
Upload.SetMaxSize 5000000, True
' Save to memory. Path parameter is omitted
Count = Upload.Save
' Two images must be selected
If Count <> 2 Then
Response.Write "You must select 2 jpeg files."
Response.End
End If
' Intercept all exceptions to display user-friendly error
On Error Resume Next
' Create two folders, ignore "already exists" error
Upload.CreateDirectory Server.MapPath("/img"), True
Upload.CreateDirectory Server.MapPath("img/small"), True
' Obtain File objects
Set File1 = Upload.Files("file1")
Set File2 = Upload.Files("file2")
' Build name from session ID
'Name = Session.SessionID
' Save
'File1.SaveAs (Server.MapPath("/img/" & File1.Ext))
'File2.SaveAs (Server.MapPath("/img/small/" & File2.Ext))
' Copy file 1 to img folder
File1.Copy (Server.MapPath("/img/" & File1.Ext))
' Delete from temp folder
File1.Delete
' Copy file 2 to small folder
File1.Copy (Server.MapPath("/small/" & File1.Ext))
' Delete from temp folder
File2.Delete
For Each File in Upload.Files
If File.ImageType <> "JPG" Then
Response.Write "The image type you are uploading is not a JPGE image."
File.Delete
Response.End
End If
Next
Dim objConn,connectstr,objRS,prodset,specialset,bncatset,featureset
connectstr = "Provider=sqloledb; Data Source=scartmil.db.8911524.hostedresource.com; Initial Catalog=scartmil; User ID=999999; Password=8888;"
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.Open connectstr
catdescription = Upload.Form(trim("catdescription"))
pcode = Upload.Form("pcode")
pname = Upload.Form(trim("pname"))
pdescription = Upload.Form(trim("pdescription"))
pPhoto = Upload.Form("pPhoto")
cstock = Upload.Form("cstock")
cprice = Upload.Form("UnitPrice")
'sanitize to avoid sql injection
catdescription = replace(catdescription,"'","''",1,-1,1)
pcode = replace(pcode,"'","''",1,-1,1)
pname = replace(pname,"'","''",1,-1,1)
pdescription = replace(pdescription,"'","''",1,-1,1)
pPhoto = replace(pPhoto,"'","''",1,-1,1)
cstock = replace(cstock,"'","''",1,-1,1)
cprice = replace(cprice,"'","''",1,-1,1)
'response.write cprice
'response.end
sql = "INSERT INTO products (ccategory, " & _
"ccode, " & _
"cname, " & _
"cdescription, " & _
"cimageurl, " & _
"cstock, " & _
"cprice) " & _
"VALUES (" & _
""&catdescription&", " & _
"'"&pcode&"', " & _
"'"&pname&"', " & _
"'"&pdescription&"', " & _
"'"&pPhoto&"', " & _
""&cstock&", " & _
""&cprice&")"
'response.write sql
'response.end
set rs = objConn.Execute(sql)
'ok record in, now retrieve the primary key
sql = "SELECT products.catalogID FROM products ORDER BY products.catalogID DESC"
'response.write sql
'response.end
set prodset = objConn.execute(sql)
if not prodset.EOF then
bCatalog = prodset("CatalogID")
end if
sql= "INSERT INTO bndCategoryProduct (bCategoryId, " & _
"bCatalogId) " & _
"VALUES (" & _
""&catdescription&", " & _
""&bCatalog&")"
'response.write sql
'response.end
set bncatset = objConn.execute(sql)
objConn.Close
Set objConn=Nothing
%>
Here is the persits link:
http://www.aspupload.com/manual_memory.html
Please don't pay attention to the insert code; it works fine.
Thanks in advance
Are you sure you have the same write permissions to both folders? also, did you notice your folders are different. If you do have the permissions set correctly, the other issue I see is your folders. You have /img and img/small Those could potentially be two different img folders.
Upload.CreateDirectory Server.MapPath("/img"), True
Upload.CreateDirectory Server.MapPath("img/small"), True
The next potential problem I see is in the code below. Just under ' Copy file 2 to small folder you have File1.copy. Shouldn't that be File2.Copy.
'# Copy file 1 to img folder
File1.Copy (Server.MapPath("/img/" & File1.Ext))
'# Delete from temp folder
File1.Delete
'# Copy file 2 to small folder
File1.Copy (Server.MapPath("/small/" & File1.Ext))
'# Delete from temp folder
File2.Delete
A few things I see:
Both copy commands use file1
They also don't specify the name, only extension.
Why not use the saveas method?
Comment out 'on error resume next' and wrap folder creation code in if/then and check if folder exists. Then you can see your errors

save file in db with unique name or id with asp classic

I'm new to asp my code is working absolutely fine, but i am facing two problems although these problems are not affecting the application. I just want to make good functionality to the application logically.
When i upload excel file, if file with the same name it's already present, i overwrite it; if i manually change file name then file is saved with new name.
What i want to do is:
save this new file with unique name or new name, i don’t know how to do this.
save this file in the db with the login user information (for future reference)
i hope my problems will be solved. many thanks
this is the url from which I got help..
CODE
upload_excel.asp
< form action="upload_excel_process.asp" method="post" enctype="multipart/form-data" name="frmMain" onSubmit="return checkData();" >
<input name="file1" type="file"> <input type="submit" name="Submit" value="Submit">
< %mem_id=session("mem_id")%>
< input type="hidden" name="client_id" value="<%=mem_id%>">
< /form>
upload_excel_process.asp
<%client_id=session("mem_id")%>
<%
Dim xlApp,xlBook,xlSheet1,xlSheet2,OpenFile,i
Dim Conn,strSQL,client_id,objExec
Dim mySmartUpload
Dim sFileName
Set mySmartUpload = Server.CreateObject("aspSmartUpload.SmartUpload")
mySmartUpload.Upload
sFileName = mySmartUpload.Files("file1").FileName
If sFileName <> "" Then
mySmartUpload.Files("file1").SaveAs(Server.MapPath("excel/"&sFileName))
OpenFile = "excel/"&sFileName
Set xlApp = Server.CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open(Server.MapPath(OpenFile))
Set xlSheet1 = xlBook.Worksheets(1)
Set Conn = Server.Createobject("ADODB.Connection")
Conn.Open "DRIVER=Microsoft Access Driver (*.mdb);DBQ=" & Server.MapPath("../db/database.mdb"),"" , ""
For i = 2 To 5
If Trim(xlSheet1.Cells.Item(i,1)) <> "" Then
strSQL = "" <br>
strSQL = strSQL &"INSERT INTO add_contacts "
strSQL = strSQL &"(client_id,name_receiver,contact_person_receiver,street_receiver,city_receiver, tel_receiver,fax_receiver,country_receiver,zip_code_receiver) "
> i have added fields to the db for file (file_name and file_id)
strSQL = strSQL &"VALUES "
strSQL = strSQL &"('"&client_id&"', '"&xlSheet1.Cells.Item(i,1)&"','"&xlSheet1.Cells.Item(i,2)&"','"&xlSheet1.Cells.Item(i,3) &"'"
strSQL = strSQL &",'"&xlSheet1.Cells.Item(i,4)&"','"&xlSheet1.Cells.Item(i,5)&"','"&xlSheet1. Cells.Item(i,6)&"','"&xlSheet1.Cells.Item(i,7)&"','"&xlSheet1.Cells.Item(i,8)&"')"
Set objExec = Conn.Execute(strSQL)
Set objExec = Nothing
End IF
Next
xlApp.Application.Quit
Conn.Close()
Set Conn = Nothing
Set xlSheet1 = Nothing
Set xlBook = Nothing
Set xlApp = Nothing
End If
Set mySmartUpload = Nothing
%>
Cheking of existens
If you want to check if a filename does aleready exists, you have to use the method FileExists from standard FilesystemObject (for more information see http://msdn.microsoft.com/en-us/library/x23stk5t(v=VS.85).aspx ).
So what do have to do?
If sFileName <> "" Then
Dim fullFilePath = Server.MapPath("excel/"&sFileName)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(filespec)) Then
//Rem Whatever you want to do here
End If
mySmartUpload.Files("file1").SaveAs(fullFilePath)
and so far...
If I understand your question you want to save the file with filename as unique to avoid the overwrite.
The best approach is to check before saving if the file exist in the destination directory or not. If it exists change the file name by appending some unique id like timestamp.
To save the file use saveas method.
strFileName = PMSmartUpload.Files.Item(1).FileName
strFilePath = strFileDirectory & "\" & strFileName
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(strFilePath)) Then
''rename suffix for file
strDateExt = cstr(month(Date)) +cstr(day(Date))+cstr(year(Date)) +cstr(Hour(Now)) +cstr(Minute(Now)) +cstr(Second(Now))
strFileExtension =fso.GetExtensionName(strFileName)
strFileBaseName = fso.GetBaseName(strFileName)
strFileName = strFileBaseName+"_"+ strDateExt +"."+strFileExtension
End If
'response.write strFileDirectory&"\"&strFileName
PMSmartUpload.Files.Item(1).saveas strFileDirectory&"\"&strFileName
In short the saveas method will save the posted file with specified name(full path)

Resources