<%@  language="VBScript" %>
<!--#INCLUDE FILE="../clsUpload/clsUpload.asp"-->
<%
Server.ScriptTimeout = 450

'This variable specifies relative path to the folder, where the gallery with uploaded files is located.
'Do not forget about the slash in the end of the folder name.
Dim strGalleryPath
strGalleryPath = "../UploadedFiles/"

Sub ProcessUpload

	' Instantiate Upload Class
	Set objUpload = New clsUpload

	If objUpload.Fields("PackageIndex").Value = "0" Then

		'Clear files and data uploaded at previous time.

		Dim objFolder, objFile

		'Delete source files.
		Set objFolder = objFileSystem.GetFolder(Server.MapPath(strGalleryPath))
		For Each objFile In objFolder.Files
			objFileSystem.DeleteFile objFile.Path, True
		Next

		'Delete thumbnails.
		Set objFolder = objFileSystem.GetFolder(Server.MapPath(strGalleryPath) & "\Thumbnails")
		For Each objFile In objFolder.Files
			objFileSystem.DeleteFile objFile.Path, True
		Next

	End If


	'NOTE: If you do not want to delete previously uploaded files, just 
	'remove or comment out the code above.

	'Create XML file which will keep information about files (image dimensions, description, etc). 
	'XML is used solely for brevity. In real-life application most likely you will use database instead.
	Dim objDescriptions
	Set objDescriptions = Server.CreateObject("Msxml2.DOMDocument")
	objDescriptions.load Server.MapPath(strGalleryPath & "files.xml")
	If objDescriptions.documentElement Is Nothing Then
		objDescriptions.appendChild objDescriptions.createElement("files")
	End If

	' Grab the file name
	Dim strFileName, strPath
	strFileName = objUpload.Fields("SourceName_0").Value
	strFileName = GetSafeFileName(strFileName)	
	
	' Save source file
	strPath = Server.MapPath(strGalleryPath & strFileName)
	objUpload("File0_0").SaveAs strPath

	'Save thumbnail
	strPath = Server.MapPath(strGalleryPath & "Thumbnails/" & strFileName & ".jpg")
	objUpload("File1_0").SaveAs strPath

	'Save file info.
	Dim objXmlFile	
	Set objXmlFile = objDescriptions.createElement("file")
	objXmlFile.setAttribute "name", objUpload.Fields("SourceName_0").Value
	objXmlFile.setAttribute "source", strFileName
	objXmlFile.setAttribute "thumbnail", strFileName & ".jpg"

	objDescriptions.documentElement.appendChild objXmlFile

	' Release upload object from memory
	Set objUpload = Nothing

	objDescriptions.save Server.MapPath(strGalleryPath & "files.xml")
	
	Response.Write("ok")

End Sub

'This method verifies whether file with such name already exists 
'and if so, construct safe filename name (to avoid collision).	
Function GetSafeFileName(strFileName)	
	Dim strNewFileName
	strNewFileName = strFileName
	Dim j 
	j = 1
	While (objFileSystem.FileExists(Server.MapPath(strGalleryPath & strNewFileName)))
		strNewFileName = j & "_" & strFileName
		j = j + 1
	Wend
	GetSafeFileName = strNewFileName
End Function


Dim objFileSystem
Set objFileSystem = Server.CreateObject("Scripting.FileSystemObject")

ProcessUpload
%>