pinkstonm
asked on
Assistance with uploading pictures
We are putting together a non-profit sit to help track missing children and part of the website asks for a face shot and a body shot picture of the child.
I need to be able to save the two files in a predetermined directory on the server.
I have the asp form where the officers can enter the information about the missing person and it allows them to select pics but I need help with an upload asp.
The missing person wil have an ID say 151 and there will be a headshot and body pic and we want to save them as 151_hs.jpg or 151_bdy.jpg no matter what the name of the input file is.
Any help would be greatly appreciated.
I need to be able to save the two files in a predetermined directory on the server.
I have the asp form where the officers can enter the information about the missing person and it allows them to select pics but I need help with an upload asp.
The missing person wil have an ID say 151 and there will be a headshot and body pic and we want to save them as 151_hs.jpg or 151_bdy.jpg no matter what the name of the input file is.
Any help would be greatly appreciated.
do you have an upload component available on the server to use, ie saupload or aspupload?
if you do that will be easier & better
if not, this link might help http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=8525&lngWId=4
if not, this link might help http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=8525&lngWId=4
could you put up the relevent code from your processing page, that handles the form submission?
ASKER
i d not have an uploader but have been looking at several of the freebies out there
ASKER
Hc,
Thanks I read the material from planet source and while it is a bit above my head I had a question before I get started. One of the scenerios said that you can actually upload pictures into an Access DB which is what we are using. I wanted to understand the pros and cons to doing this versus uploading the pics to a folder and having an entry in the DB pointing to them.
Thanks
Thanks I read the material from planet source and while it is a bit above my head I had a question before I get started. One of the scenerios said that you can actually upload pictures into an Access DB which is what we are using. I wanted to understand the pros and cons to doing this versus uploading the pics to a folder and having an entry in the DB pointing to them.
Thanks
hi,
personally i prefer loading an image and having an entry in the db relating to it, it seems cleaner somehow than putting the actual image into the db, which I imagine would make the db a bit bloated.
Essentially you upload an image to a folder on your site, and then put the filename into the db record, along with any other info you want to track. To use the image you read the db record, get the filename, add it to the folder name, and that's where the image is.
I'd suggest using some sample code from the link above, and drop a copy of your code as you go, so I can chip in with advice.
It's fairly easy, and I'm sure you'll have no problem with it.
personally i prefer loading an image and having an entry in the db relating to it, it seems cleaner somehow than putting the actual image into the db, which I imagine would make the db a bit bloated.
Essentially you upload an image to a folder on your site, and then put the filename into the db record, along with any other info you want to track. To use the image you read the db record, get the filename, add it to the folder name, and that's where the image is.
I'd suggest using some sample code from the link above, and drop a copy of your code as you go, so I can chip in with advice.
It's fairly easy, and I'm sure you'll have no problem with it.
ASKER
Okay keep your eyes out as I am no pro :)
ASKER
Okay well I tried....
I followed the simple instructions and go an error.
***testForm.asp***
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
</head>
<body>
<FORM method="post" encType="multipart/form-da ta" action="testUpload.asp">
<INPUT type="File" name="File1">
<INPUT type="Submit" value="Upload">
</FORM>
</body>
</html>
***testUpload.asp***
<!--#INCLUDE FILE="upload/clsUpload.asp "-->
<%
Dim Upload
Dim Folder
Set Upload = New clsUpload
Folder = Server.MapPath("submission s") & "\"
Upload("File1").SaveAs Folder & Upload("File1").FileName
Set Upload = Nothing
%>
The error I get is:
Microsoft VBScript runtime error '800a0046'
Permission denied
/upload/clsField.asp, line 227
Folder submissions has write access set to general
I followed the simple instructions and go an error.
***testForm.asp***
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
</head>
<body>
<FORM method="post" encType="multipart/form-da
<INPUT type="File" name="File1">
<INPUT type="Submit" value="Upload">
</FORM>
</body>
</html>
***testUpload.asp***
<!--#INCLUDE FILE="upload/clsUpload.asp
<%
Dim Upload
Dim Folder
Set Upload = New clsUpload
Folder = Server.MapPath("submission
Upload("File1").SaveAs Folder & Upload("File1").FileName
Set Upload = Nothing
%>
The error I get is:
Microsoft VBScript runtime error '800a0046'
Permission denied
/upload/clsField.asp, line 227
Folder submissions has write access set to general
ASKER
Here is really what I am trying to accomplish with their code
***testForm.asp***
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
</head>
<body>
<FORM method="post" encType="multipart/form-da ta" action="testUpload.asp">
<INPUT type="File" name="File1">
<INPUT type="File" name="File2">
<INPUT type="Submit" value="Upload">
</FORM>
</body>
</html>
***testUpload.asp***
<!--#INCLUDE FILE="upload/clsUpload.asp "-->
<%
Dim Upload
Dim Folder
clientid = 1500
Set Upload = New clsUpload
Folder = Server.MapPath("submission s") & "\"
' File 1 would be headshot
Upload.RenameFile Folder & FileName, clientid & "_head.jpg"
Upload("File1").SaveAs Folder & FileName
' File 1 would be body
Upload.RenameFile Folder & FileName, clientid & "_body.jpg"
Upload("File2").SaveAs Folder & FileName
Set Upload = Nothing
%>
***testForm.asp***
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
</head>
<body>
<FORM method="post" encType="multipart/form-da
<INPUT type="File" name="File1">
<INPUT type="File" name="File2">
<INPUT type="Submit" value="Upload">
</FORM>
</body>
</html>
***testUpload.asp***
<!--#INCLUDE FILE="upload/clsUpload.asp
<%
Dim Upload
Dim Folder
clientid = 1500
Set Upload = New clsUpload
Folder = Server.MapPath("submission
' File 1 would be headshot
Upload.RenameFile Folder & FileName, clientid & "_head.jpg"
Upload("File1").SaveAs Folder & FileName
' File 1 would be body
Upload.RenameFile Folder & FileName, clientid & "_body.jpg"
Upload("File2").SaveAs Folder & FileName
Set Upload = Nothing
%>
ASKER
When I tried that method I got
Microsoft VBScript runtime error '800a0035'
File not found
/upload/clsUpload.asp, line 820
Microsoft VBScript runtime error '800a0035'
File not found
/upload/clsUpload.asp, line 820
for the first error,
The error I get is:
Microsoft VBScript runtime error '800a0046'
Permission denied
/upload/clsField.asp, line 227
Folder submissions has write access set to general
I should have mentioned this earlier ... the folder where you want to load images must be a folder which you can write to, as opposed to read-only access which most folders have by default.
This means that to set up the uploads script, you must first set permissions.
If you are using a hosting company, it's easy. You ask them to set permissions for /xxx/ folder so that it can be used for uploading files. They know what that means, it's a common request, and they know how to do it. When it's done, you won't see the "Permission denied" error again.
Here's a tip - if you think you might want flexibility to use subfolders, or to rename them, then create a generic folder and call it something like "uploads", or "file_library", or anything that makes sense to you. Then make a subfolder you're going to use for uploads. Now ask that the hosting company to set permissions on the first folder including any subdirectories. That way if you need to you can change the name of the subfolder, create new ones etc without having to get the permissions reset.
If you host your own server, then you probably know how to set permissions.
The error I get is:
Microsoft VBScript runtime error '800a0046'
Permission denied
/upload/clsField.asp, line 227
Folder submissions has write access set to general
I should have mentioned this earlier ... the folder where you want to load images must be a folder which you can write to, as opposed to read-only access which most folders have by default.
This means that to set up the uploads script, you must first set permissions.
If you are using a hosting company, it's easy. You ask them to set permissions for /xxx/ folder so that it can be used for uploading files. They know what that means, it's a common request, and they know how to do it. When it's done, you won't see the "Permission denied" error again.
Here's a tip - if you think you might want flexibility to use subfolders, or to rename them, then create a generic folder and call it something like "uploads", or "file_library", or anything that makes sense to you. Then make a subfolder you're going to use for uploads. Now ask that the hosting company to set permissions on the first folder including any subdirectories. That way if you need to you can change the name of the subfolder, create new ones etc without having to get the permissions reset.
If you host your own server, then you probably know how to set permissions.
ASKER
well the folder is set to read/write general and I am still getting errors.
ASKER
The error I am getting now is
Microsoft VBScript runtime error '800a0035'
File not found
/upload/clsUpload.asp, line 820
Based on the following code:
***testForm.asp***
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
</head>
<body>
<FORM method="post" encType="multipart/form-da ta" action="testUpload.asp">
<INPUT type="File" name="File1">
<INPUT type="File" name="File2">
<INPUT type="Submit" value="Upload">
</FORM>
</body>
</html>
***testUpload.asp***
<!--#INCLUDE FILE="upload/clsUpload.asp "-->
<%
Dim Upload
Dim Folder
clientid = 1500
Set Upload = New clsUpload
Folder = Server.MapPath("submission s") & "\"
' File 1 would be headshot
Upload.RenameFile Folder & FileName, clientid & "_head.jpg"
Upload("File1").SaveAs Folder & FileName
' File 1 would be body
Upload.RenameFile Folder & FileName, clientid & "_body.jpg"
Upload("File2").SaveAs Folder & FileName
Set Upload = Nothing
%>
Microsoft VBScript runtime error '800a0035'
File not found
/upload/clsUpload.asp, line 820
Based on the following code:
***testForm.asp***
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
</head>
<body>
<FORM method="post" encType="multipart/form-da
<INPUT type="File" name="File1">
<INPUT type="File" name="File2">
<INPUT type="Submit" value="Upload">
</FORM>
</body>
</html>
***testUpload.asp***
<!--#INCLUDE FILE="upload/clsUpload.asp
<%
Dim Upload
Dim Folder
clientid = 1500
Set Upload = New clsUpload
Folder = Server.MapPath("submission
' File 1 would be headshot
Upload.RenameFile Folder & FileName, clientid & "_head.jpg"
Upload("File1").SaveAs Folder & FileName
' File 1 would be body
Upload.RenameFile Folder & FileName, clientid & "_body.jpg"
Upload("File2").SaveAs Folder & FileName
Set Upload = Nothing
%>
ASKER
Does anyone have any better suggestions or a sample of how to do this. The old version out on planet source apparently does not work.
Any help would be greatly appreciated!
Any help would be greatly appreciated!
ASKER
Got a base upload to work so the permissions error from the other sample code was not true.
Here is the Base Form:
<%@ Language=VBScript %>
<%
option explicit
Response.Expires = -1
Server.ScriptTimeout = 600
%>
<!-- #include file="Upload/freeaspupload .asp" -->
<%
uploadsDirVar = "xxxxx"
function OutputForm()
%>
<form name="frmSend" method="POST" enctype="multipart/form-da ta" action="uploadTester.asp" onSubmit="return onSubmitForm();">
<B>File names:</B><br>
File 1: <input name="attach1" type="file" size=35><br>
File 2: <input name="attach2" type="file" size=35><br>
<br>
<input style="margin-top:4" type=submit value="Upload">
</form>
<%
end function
function TestEnvironment()
Dim fso, fileName, testFile, streamTest
TestEnvironment = ""
Set fso = Server.CreateObject("Scrip ting.FileS ystemObjec t")
if not fso.FolderExists(uploadsDi rVar) 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(fileNam e, 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
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
SaveFiles = ""
ks = Upload.UploadedFiles.keys
if (UBound(ks) <> -1) then
SaveFiles = "<B>Files uploaded:</B> "
for each fileKey in Upload.UploadedFiles.keys
SaveFiles = SaveFiles & Upload.UploadedFiles(fileK ey).FileNa me & " (" & Upload.UploadedFiles(fileK ey).Length & "B) "
next
else
SaveFiles = "The file name specified in the upload form does not correspond to a valid file in the system."
end if
SaveFiles = SaveFiles & "<br>Enter a number = " & Upload.Form("enter_a_numbe r") & "<br>"
SaveFiles = SaveFiles & "Checkbox values = " & Upload.Form("checkbox_valu es") & "<br>"
end function
%>
<HTML>
<HEAD>
<TITLE>Test Free ASP Upload</TITLE>
<style>
BODY {background-color: white;font-family:arial; font-size:12}
</style>
<script>
function onSubmitForm() {
var formDOMObj = document.frmSend;
if (formDOMObj.attach1.value == "" && formDOMObj.attach2.value == "" && formDOMObj.attach3.value == "" && formDOMObj.attach4.value == "" )
alert("Please press the browse button and pick a file.")
else
return true;
return false;
}
</script>
</HEAD>
<BODY>
<br><br>
<div style="border-bottom: #A91905 2px solid;font-size:16">Upload files to your server</div>
<%
Dim diagnostics
if Request.ServerVariables("R EQUEST_MET HOD") <> "POST" then
diagnostics = TestEnvironment()
if diagnostics<>"" then
response.write "<div style=""margin-left:20; margin-top:30; margin-right:30; margin-bottom:30;"">"
response.write diagnostics
response.write "<p>After you correct this problem, reload the page."
response.write "</div>"
else
response.write "<div style=""margin-left:150""> "
OutputForm()
response.write "</div>"
end if
else
response.write "<div style=""margin-left:150""> "
OutputForm()
response.write SaveFiles()
response.write "<br><br></div>"
end if
%>
</BODY>
</HTML>
Here is the called ASP that does the upload:
<%
' For examples, documentation, and your own free copy, go to:
' http://www.freeaspupload.net
' Note: You can copy and use this script for free and you can make changes
' to the code, but you cannot remove the above comment.
'Changes:
'Aug 2, 2005: Add support for checkboxes and other input elements with multiple values
Class FreeASPUpload
Public UploadedFiles
Public FormElements
Private VarArrayBinRequest
Private StreamRequest
Private uploadedYet
Private Sub Class_Initialize()
Set UploadedFiles = Server.CreateObject("Scrip ting.Dicti onary")
Set FormElements = Server.CreateObject("Scrip ting.Dicti onary")
Set StreamRequest = Server.CreateObject("ADODB .Stream")
StreamRequest.Type = 1 'adTypeBinary
StreamRequest.Open
uploadedYet = false
End Sub
Private Sub Class_Terminate()
If IsObject(UploadedFiles) Then
UploadedFiles.RemoveAll()
Set UploadedFiles = Nothing
End If
If IsObject(FormElements) Then
FormElements.RemoveAll()
Set FormElements = Nothing
End If
StreamRequest.Close
Set StreamRequest = Nothing
End Sub
Public Property Get Form(sIndex)
Form = ""
If FormElements.Exists(LCase( sIndex)) Then Form = FormElements.Item(LCase(sI ndex))
End Property
Public Property Get Files()
Files = UploadedFiles.Items
End Property
'Calls Upload to extract the data from the binary request and then saves the uploaded files
Public Sub Save(path)
Dim streamFile, fileItem
if Right(path, 1) <> "\" then path = path & "\"
if not uploadedYet then Upload
For Each fileItem In UploadedFiles.Items
Set streamFile = Server.CreateObject("ADODB .Stream")
streamFile.Type = 1
streamFile.Open
StreamRequest.Position=fil eItem.Star t
StreamRequest.CopyTo streamFile, fileItem.Length
streamFile.SaveToFile path & fileItem.FileName, 2
streamFile.close
Set streamFile = Nothing
fileItem.Path = path & fileItem.FileName
Next
End Sub
Public Function SaveBinRequest(path) ' For debugging purposes
StreamRequest.SaveToFile path & "\debugStream.bin", 2
End Function
Public Sub DumpData() 'only works if files are plain text
Dim i, aKeys, f
response.write "Form Items:<br>"
aKeys = FormElements.Keys
For i = 0 To FormElements.Count -1 ' Iterate the array
response.write aKeys(i) & " = " & FormElements.Item(aKeys(i) ) & "<BR>"
Next
response.write "Uploaded Files:<br>"
For Each f In UploadedFiles.Items
response.write "Name: " & f.FileName & "<br>"
response.write "Type: " & f.ContentType & "<br>"
response.write "Start: " & f.Start & "<br>"
response.write "Size: " & f.Length & "<br>"
Next
End Sub
Private Sub Upload()
Dim nCurPos, nDataBoundPos, nLastSepPos
Dim nPosFile, nPosBound
Dim sFieldName, osPathSep, auxStr
'RFC1867 Tokens
Dim vDataSep
Dim tNewLine, tDoubleQuotes, tTerm, tFilename, tName, tContentDisp, tContentType
tNewLine = Byte2String(Chr(13))
tDoubleQuotes = Byte2String(Chr(34))
tTerm = Byte2String("--")
tFilename = Byte2String("filename=""")
tName = Byte2String("name=""")
tContentDisp = Byte2String("Content-Dispo sition")
tContentType = Byte2String("Content-Type: ")
uploadedYet = true
on error resume next
VarArrayBinRequest = Request.BinaryRead(Request .TotalByte s)
if Err.Number <> 0 then
response.write "<br><br><B>System reported this error:</B><p>"
response.write Err.Description & "<p>"
response.write "The most likely cause for this error is the incorrect setup of AspMaxRequestEntityAllowed in IIS MetaBase. Please see instructions in the <A HREF='http://www.freeaspupload.net/freeaspupload/requirements.asp'>requirements page of freeaspupload.net</A>.<p>"
Exit Sub
end if
on error goto 0 'reset error handling
nCurPos = FindToken(tNewLine,1) 'Note: nCurPos is 1-based (and so is InstrB, MidB, etc)
If nCurPos <= 1 Then Exit Sub
'vDataSep is a separator like -------------------------- ---2176313 8716045
vDataSep = MidB(VarArrayBinRequest, 1, nCurPos-1)
'Start of current separator
nDataBoundPos = 1
'Beginning of last line
nLastSepPos = FindToken(vDataSep & tTerm, 1)
Do Until nDataBoundPos = nLastSepPos
nCurPos = SkipToken(tContentDisp, nDataBoundPos)
nCurPos = SkipToken(tName, nCurPos)
sFieldName = ExtractField(tDoubleQuotes , nCurPos)
nPosFile = FindToken(tFilename, nCurPos)
nPosBound = FindToken(vDataSep, nCurPos)
If nPosFile <> 0 And nPosFile < nPosBound Then
Dim oUploadFile
Set oUploadFile = New UploadedFile
nCurPos = SkipToken(tFilename, nCurPos)
auxStr = ExtractField(tDoubleQuotes , nCurPos)
' We are interested only in the name of the file, not the whole path
' Path separator is \ in windows, / in UNIX
' While IE seems to put the whole pathname in the stream, Mozilla seem to
' only put the actual file name, so UNIX paths may be rare. But not impossible.
osPathSep = "\"
if InStr(auxStr, osPathSep) = 0 then osPathSep = "/"
oUploadFile.FileName = Right(auxStr, Len(auxStr)-InStrRev(auxSt r, osPathSep))
if (Len(oUploadFile.FileName) > 0) then 'File field not left empty
nCurPos = SkipToken(tContentType, nCurPos)
auxStr = ExtractField(tNewLine, nCurPos)
' NN on UNIX puts things like this in the streaa:
' ?? python py type=?? python application/x-python
oUploadFile.ContentType = Right(auxStr, Len(auxStr)-InStrRev(auxSt r, " "))
nCurPos = FindToken(tNewLine, nCurPos) + 4 'skip empty line
oUploadFile.Start = nCurPos-1
oUploadFile.Length = FindToken(vDataSep, nCurPos) - 2 - nCurPos
If oUploadFile.Length > 0 Then UploadedFiles.Add LCase(sFieldName), oUploadFile
End If
Else
Dim nEndOfData
nCurPos = FindToken(tNewLine, nCurPos) + 4 'skip empty line
nEndOfData = FindToken(vDataSep, nCurPos) - 2
If Not FormElements.Exists(LCase( sFieldName )) Then
FormElements.Add LCase(sFieldName), String2Byte(MidB(VarArrayB inRequest, nCurPos, nEndOfData-nCurPos))
else
FormElements.Item(LCase(sF ieldName)) = FormElements.Item(LCase(sF ieldName)) & ", " & String2Byte(MidB(VarArrayB inRequest, nCurPos, nEndOfData-nCurPos))
end if
End If
'Advance to next separator
nDataBoundPos = FindToken(vDataSep, nCurPos)
Loop
StreamRequest.Write(VarArr ayBinReque st)
End Sub
Private Function SkipToken(sToken, nStart)
SkipToken = InstrB(nStart, VarArrayBinRequest, sToken)
If SkipToken = 0 then
Response.write "Error in parsing uploaded binary request."
Response.End
end if
SkipToken = SkipToken + LenB(sToken)
End Function
Private Function FindToken(sToken, nStart)
FindToken = InstrB(nStart, VarArrayBinRequest, sToken)
End Function
Private Function ExtractField(sToken, nStart)
Dim nEnd
nEnd = InstrB(nStart, VarArrayBinRequest, sToken)
If nEnd = 0 then
Response.write "Error in parsing uploaded binary request."
Response.End
end if
ExtractField = String2Byte(MidB(VarArrayB inRequest, nStart, nEnd-nStart))
End Function
'String to byte string conversion
Private Function Byte2String(sString)
Dim i
For i = 1 to Len(sString)
Byte2String = Byte2String & ChrB(AscB(Mid(sString,i,1) ))
Next
End Function
'Byte string to string conversion
Private Function String2Byte(bsString)
Dim i
String2Byte =""
For i = 1 to LenB(bsString)
String2Byte = String2Byte & Chr(AscB(MidB(bsString,i,1 )))
Next
End Function
End Class
Class UploadedFile
Public ContentType
Public Start
Public Length
Public Path
Private nameOfFile
' Need to remove characters that are valid in UNIX, but not in Windows
Public Property Let FileName(fN)
nameOfFile = fN
nameOfFile = SubstNoReg(nameOfFile, "\", "_")
nameOfFile = SubstNoReg(nameOfFile, "/", "_")
nameOfFile = SubstNoReg(nameOfFile, ":", "_")
nameOfFile = SubstNoReg(nameOfFile, "*", "_")
nameOfFile = SubstNoReg(nameOfFile, "?", "_")
nameOfFile = SubstNoReg(nameOfFile, """", "_")
nameOfFile = SubstNoReg(nameOfFile, "<", "_")
nameOfFile = SubstNoReg(nameOfFile, ">", "_")
nameOfFile = SubstNoReg(nameOfFile, "|", "_")
End Property
Public Property Get FileName()
FileName = nameOfFile
End Property
'Public Property Get FileN()ame
End Class
' Does not depend on RegEx, which is not available on older VBScript
' Is not recursive, which means it will not run out of stack space
Function SubstNoReg(initialStr, oldStr, newStr)
Dim currentPos, oldStrPos, skip
If IsNull(initialStr) Or Len(initialStr) = 0 Then
SubstNoReg = ""
ElseIf IsNull(oldStr) Or Len(oldStr) = 0 Then
SubstNoReg = initialStr
Else
If IsNull(newStr) Then newStr = ""
currentPos = 1
oldStrPos = 0
SubstNoReg = ""
skip = Len(oldStr)
Do While currentPos <= Len(initialStr)
oldStrPos = InStr(currentPos, initialStr, oldStr)
If oldStrPos = 0 Then
SubstNoReg = SubstNoReg & Mid(initialStr, currentPos, Len(initialStr) - currentPos + 1)
currentPos = Len(initialStr) + 1
Else
SubstNoReg = SubstNoReg & Mid(initialStr, currentPos, oldStrPos - currentPos) & newStr
currentPos = oldStrPos + skip
End If
Loop
End If
End Function
%>
What I need help with is when the files upload I need them named something other than the names selected. The naming should be a client#_head.ext and client#_body.ext.
I only want them to input jpg or gif files.
Here is the Base Form:
<%@ Language=VBScript %>
<%
option explicit
Response.Expires = -1
Server.ScriptTimeout = 600
%>
<!-- #include file="Upload/freeaspupload
<%
uploadsDirVar = "xxxxx"
function OutputForm()
%>
<form name="frmSend" method="POST" enctype="multipart/form-da
<B>File names:</B><br>
File 1: <input name="attach1" type="file" size=35><br>
File 2: <input name="attach2" type="file" size=35><br>
<br>
<input style="margin-top:4" type=submit value="Upload">
</form>
<%
end function
function TestEnvironment()
Dim fso, fileName, testFile, streamTest
TestEnvironment = ""
Set fso = Server.CreateObject("Scrip
if not fso.FolderExists(uploadsDi
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(fileNam
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
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
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
SaveFiles = ""
ks = Upload.UploadedFiles.keys
if (UBound(ks) <> -1) then
SaveFiles = "<B>Files uploaded:</B> "
for each fileKey in Upload.UploadedFiles.keys
SaveFiles = SaveFiles & Upload.UploadedFiles(fileK
next
else
SaveFiles = "The file name specified in the upload form does not correspond to a valid file in the system."
end if
SaveFiles = SaveFiles & "<br>Enter a number = " & Upload.Form("enter_a_numbe
SaveFiles = SaveFiles & "Checkbox values = " & Upload.Form("checkbox_valu
end function
%>
<HTML>
<HEAD>
<TITLE>Test Free ASP Upload</TITLE>
<style>
BODY {background-color: white;font-family:arial; font-size:12}
</style>
<script>
function onSubmitForm() {
var formDOMObj = document.frmSend;
if (formDOMObj.attach1.value == "" && formDOMObj.attach2.value == "" && formDOMObj.attach3.value == "" && formDOMObj.attach4.value == "" )
alert("Please press the browse button and pick a file.")
else
return true;
return false;
}
</script>
</HEAD>
<BODY>
<br><br>
<div style="border-bottom: #A91905 2px solid;font-size:16">Upload
<%
Dim diagnostics
if Request.ServerVariables("R
diagnostics = TestEnvironment()
if diagnostics<>"" then
response.write "<div style=""margin-left:20; margin-top:30; margin-right:30; margin-bottom:30;"">"
response.write diagnostics
response.write "<p>After you correct this problem, reload the page."
response.write "</div>"
else
response.write "<div style=""margin-left:150"">
OutputForm()
response.write "</div>"
end if
else
response.write "<div style=""margin-left:150"">
OutputForm()
response.write SaveFiles()
response.write "<br><br></div>"
end if
%>
</BODY>
</HTML>
Here is the called ASP that does the upload:
<%
' For examples, documentation, and your own free copy, go to:
' http://www.freeaspupload.net
' Note: You can copy and use this script for free and you can make changes
' to the code, but you cannot remove the above comment.
'Changes:
'Aug 2, 2005: Add support for checkboxes and other input elements with multiple values
Class FreeASPUpload
Public UploadedFiles
Public FormElements
Private VarArrayBinRequest
Private StreamRequest
Private uploadedYet
Private Sub Class_Initialize()
Set UploadedFiles = Server.CreateObject("Scrip
Set FormElements = Server.CreateObject("Scrip
Set StreamRequest = Server.CreateObject("ADODB
StreamRequest.Type = 1 'adTypeBinary
StreamRequest.Open
uploadedYet = false
End Sub
Private Sub Class_Terminate()
If IsObject(UploadedFiles) Then
UploadedFiles.RemoveAll()
Set UploadedFiles = Nothing
End If
If IsObject(FormElements) Then
FormElements.RemoveAll()
Set FormElements = Nothing
End If
StreamRequest.Close
Set StreamRequest = Nothing
End Sub
Public Property Get Form(sIndex)
Form = ""
If FormElements.Exists(LCase(
End Property
Public Property Get Files()
Files = UploadedFiles.Items
End Property
'Calls Upload to extract the data from the binary request and then saves the uploaded files
Public Sub Save(path)
Dim streamFile, fileItem
if Right(path, 1) <> "\" then path = path & "\"
if not uploadedYet then Upload
For Each fileItem In UploadedFiles.Items
Set streamFile = Server.CreateObject("ADODB
streamFile.Type = 1
streamFile.Open
StreamRequest.Position=fil
StreamRequest.CopyTo streamFile, fileItem.Length
streamFile.SaveToFile path & fileItem.FileName, 2
streamFile.close
Set streamFile = Nothing
fileItem.Path = path & fileItem.FileName
Next
End Sub
Public Function SaveBinRequest(path) ' For debugging purposes
StreamRequest.SaveToFile path & "\debugStream.bin", 2
End Function
Public Sub DumpData() 'only works if files are plain text
Dim i, aKeys, f
response.write "Form Items:<br>"
aKeys = FormElements.Keys
For i = 0 To FormElements.Count -1 ' Iterate the array
response.write aKeys(i) & " = " & FormElements.Item(aKeys(i)
Next
response.write "Uploaded Files:<br>"
For Each f In UploadedFiles.Items
response.write "Name: " & f.FileName & "<br>"
response.write "Type: " & f.ContentType & "<br>"
response.write "Start: " & f.Start & "<br>"
response.write "Size: " & f.Length & "<br>"
Next
End Sub
Private Sub Upload()
Dim nCurPos, nDataBoundPos, nLastSepPos
Dim nPosFile, nPosBound
Dim sFieldName, osPathSep, auxStr
'RFC1867 Tokens
Dim vDataSep
Dim tNewLine, tDoubleQuotes, tTerm, tFilename, tName, tContentDisp, tContentType
tNewLine = Byte2String(Chr(13))
tDoubleQuotes = Byte2String(Chr(34))
tTerm = Byte2String("--")
tFilename = Byte2String("filename=""")
tName = Byte2String("name=""")
tContentDisp = Byte2String("Content-Dispo
tContentType = Byte2String("Content-Type:
uploadedYet = true
on error resume next
VarArrayBinRequest = Request.BinaryRead(Request
if Err.Number <> 0 then
response.write "<br><br><B>System reported this error:</B><p>"
response.write Err.Description & "<p>"
response.write "The most likely cause for this error is the incorrect setup of AspMaxRequestEntityAllowed
Exit Sub
end if
on error goto 0 'reset error handling
nCurPos = FindToken(tNewLine,1) 'Note: nCurPos is 1-based (and so is InstrB, MidB, etc)
If nCurPos <= 1 Then Exit Sub
'vDataSep is a separator like --------------------------
vDataSep = MidB(VarArrayBinRequest, 1, nCurPos-1)
'Start of current separator
nDataBoundPos = 1
'Beginning of last line
nLastSepPos = FindToken(vDataSep & tTerm, 1)
Do Until nDataBoundPos = nLastSepPos
nCurPos = SkipToken(tContentDisp, nDataBoundPos)
nCurPos = SkipToken(tName, nCurPos)
sFieldName = ExtractField(tDoubleQuotes
nPosFile = FindToken(tFilename, nCurPos)
nPosBound = FindToken(vDataSep, nCurPos)
If nPosFile <> 0 And nPosFile < nPosBound Then
Dim oUploadFile
Set oUploadFile = New UploadedFile
nCurPos = SkipToken(tFilename, nCurPos)
auxStr = ExtractField(tDoubleQuotes
' We are interested only in the name of the file, not the whole path
' Path separator is \ in windows, / in UNIX
' While IE seems to put the whole pathname in the stream, Mozilla seem to
' only put the actual file name, so UNIX paths may be rare. But not impossible.
osPathSep = "\"
if InStr(auxStr, osPathSep) = 0 then osPathSep = "/"
oUploadFile.FileName = Right(auxStr, Len(auxStr)-InStrRev(auxSt
if (Len(oUploadFile.FileName)
nCurPos = SkipToken(tContentType, nCurPos)
auxStr = ExtractField(tNewLine, nCurPos)
' NN on UNIX puts things like this in the streaa:
' ?? python py type=?? python application/x-python
oUploadFile.ContentType = Right(auxStr, Len(auxStr)-InStrRev(auxSt
nCurPos = FindToken(tNewLine, nCurPos) + 4 'skip empty line
oUploadFile.Start = nCurPos-1
oUploadFile.Length = FindToken(vDataSep, nCurPos) - 2 - nCurPos
If oUploadFile.Length > 0 Then UploadedFiles.Add LCase(sFieldName), oUploadFile
End If
Else
Dim nEndOfData
nCurPos = FindToken(tNewLine, nCurPos) + 4 'skip empty line
nEndOfData = FindToken(vDataSep, nCurPos) - 2
If Not FormElements.Exists(LCase(
FormElements.Add LCase(sFieldName), String2Byte(MidB(VarArrayB
else
FormElements.Item(LCase(sF
end if
End If
'Advance to next separator
nDataBoundPos = FindToken(vDataSep, nCurPos)
Loop
StreamRequest.Write(VarArr
End Sub
Private Function SkipToken(sToken, nStart)
SkipToken = InstrB(nStart, VarArrayBinRequest, sToken)
If SkipToken = 0 then
Response.write "Error in parsing uploaded binary request."
Response.End
end if
SkipToken = SkipToken + LenB(sToken)
End Function
Private Function FindToken(sToken, nStart)
FindToken = InstrB(nStart, VarArrayBinRequest, sToken)
End Function
Private Function ExtractField(sToken, nStart)
Dim nEnd
nEnd = InstrB(nStart, VarArrayBinRequest, sToken)
If nEnd = 0 then
Response.write "Error in parsing uploaded binary request."
Response.End
end if
ExtractField = String2Byte(MidB(VarArrayB
End Function
'String to byte string conversion
Private Function Byte2String(sString)
Dim i
For i = 1 to Len(sString)
Byte2String = Byte2String & ChrB(AscB(Mid(sString,i,1)
Next
End Function
'Byte string to string conversion
Private Function String2Byte(bsString)
Dim i
String2Byte =""
For i = 1 to LenB(bsString)
String2Byte = String2Byte & Chr(AscB(MidB(bsString,i,1
Next
End Function
End Class
Class UploadedFile
Public ContentType
Public Start
Public Length
Public Path
Private nameOfFile
' Need to remove characters that are valid in UNIX, but not in Windows
Public Property Let FileName(fN)
nameOfFile = fN
nameOfFile = SubstNoReg(nameOfFile, "\", "_")
nameOfFile = SubstNoReg(nameOfFile, "/", "_")
nameOfFile = SubstNoReg(nameOfFile, ":", "_")
nameOfFile = SubstNoReg(nameOfFile, "*", "_")
nameOfFile = SubstNoReg(nameOfFile, "?", "_")
nameOfFile = SubstNoReg(nameOfFile, """", "_")
nameOfFile = SubstNoReg(nameOfFile, "<", "_")
nameOfFile = SubstNoReg(nameOfFile, ">", "_")
nameOfFile = SubstNoReg(nameOfFile, "|", "_")
End Property
Public Property Get FileName()
FileName = nameOfFile
End Property
'Public Property Get FileN()ame
End Class
' Does not depend on RegEx, which is not available on older VBScript
' Is not recursive, which means it will not run out of stack space
Function SubstNoReg(initialStr, oldStr, newStr)
Dim currentPos, oldStrPos, skip
If IsNull(initialStr) Or Len(initialStr) = 0 Then
SubstNoReg = ""
ElseIf IsNull(oldStr) Or Len(oldStr) = 0 Then
SubstNoReg = initialStr
Else
If IsNull(newStr) Then newStr = ""
currentPos = 1
oldStrPos = 0
SubstNoReg = ""
skip = Len(oldStr)
Do While currentPos <= Len(initialStr)
oldStrPos = InStr(currentPos, initialStr, oldStr)
If oldStrPos = 0 Then
SubstNoReg = SubstNoReg & Mid(initialStr, currentPos, Len(initialStr) - currentPos + 1)
currentPos = Len(initialStr) + 1
Else
SubstNoReg = SubstNoReg & Mid(initialStr, currentPos, oldStrPos - currentPos) & newStr
currentPos = oldStrPos + skip
End If
Loop
End If
End Function
%>
What I need help with is when the files upload I need them named something other than the names selected. The naming should be a client#_head.ext and client#_body.ext.
I only want them to input jpg or gif files.
for checking file extensions, you can try this snippet,
Ext = Upload("File1").FileExt
Select Case Ext
Case "GIF", "JPG"
FileName = Upload("File1").FileName
Folder = Server.MapPath("Uploads") & "\"
Upload("File1").SaveAs Folder & FileName
Case Else
Response.Write "File type not supported."
End Select
Ext = Upload("File1").FileExt
Select Case Ext
Case "GIF", "JPG"
FileName = Upload("File1").FileName
Folder = Server.MapPath("Uploads") & "\"
Upload("File1").SaveAs Folder & FileName
Case Else
Response.Write "File type not supported."
End Select
sorry, ignore that, you're using a different upload script now so that won't work.
ASKER
will you be able to help with this script?
The other one continually got permission errors and this one works
The other one continually got permission errors and this one works
According to the documentation for this script, the sample upload page uploadTester.asp has a form validation JavaScript function ("onSubmitForm") where you can test for filetypes.
Could you replace the script in your html with this, and see if it works?
<script>
/* original onSubmitForm function
function onSubmitForm() {
var formDOMObj = document.frmSend;
if (formDOMObj.attach1.value == "" && formDOMObj.attach2.value == "" && formDOMObj.attach3.value == "" && formDOMObj.attach4.value == "" )
alert("Please press the browse button and pick a file.")
else
return true;
return false;
}
*/
function onSubmitForm() {
var formDOMObj = document.frmSend;
//set 2 flags, 1 for whether attachments are empty, 1 for whether they are correct format
var checkFilesAreAttached = 0;
var checkFileFormats = 0;
//check that two files have been selected
if ( formDOMObj.attach1.value == "" || formDOMObj.attach2.value == "" ){
checkFilesAreAttached = 0;
} else {
checkFilesAreAttached = 1;
}
//check that file 1 is in the correct format, either jpg or gif
if ( formDOMObj.attach1.value.i ndexOf("jp g") == -1 && formDOMObj.attach1.value.i ndexOf("gi f") == -1 ) {
checkFileFormats = 0;
} else {
//check that file 2 is in the correct format, either jpg or gif
if ( formDOMObj.attach2.value.i ndexOf("jp g") == -1 && formDOMObj.attach2.value.i ndexOf("gi f") == -1 ) {
checkFileFormats = 0;
} else {
checkFileFormats = 1;
}
}
if(checkFilesAreAttached == 0) {
//first check has failed, which means they did not select two files to be uploaded
alert("Please press the browse button and pick a file.");
return false;
} else {
if(checkFileFormats == 0) {
//second check has failed, which means that oine of the files is neither jpg nor gif
alert("Please ensure you select only JPG or GIF images to upload");
return false;
} else {
return true;
}
}
}
}
</script>
Could you replace the script in your html with this, and see if it works?
<script>
/* original onSubmitForm function
function onSubmitForm() {
var formDOMObj = document.frmSend;
if (formDOMObj.attach1.value == "" && formDOMObj.attach2.value == "" && formDOMObj.attach3.value == "" && formDOMObj.attach4.value == "" )
alert("Please press the browse button and pick a file.")
else
return true;
return false;
}
*/
function onSubmitForm() {
var formDOMObj = document.frmSend;
//set 2 flags, 1 for whether attachments are empty, 1 for whether they are correct format
var checkFilesAreAttached = 0;
var checkFileFormats = 0;
//check that two files have been selected
if ( formDOMObj.attach1.value == "" || formDOMObj.attach2.value == "" ){
checkFilesAreAttached = 0;
} else {
checkFilesAreAttached = 1;
}
//check that file 1 is in the correct format, either jpg or gif
if ( formDOMObj.attach1.value.i
checkFileFormats = 0;
} else {
//check that file 2 is in the correct format, either jpg or gif
if ( formDOMObj.attach2.value.i
checkFileFormats = 0;
} else {
checkFileFormats = 1;
}
}
if(checkFilesAreAttached == 0) {
//first check has failed, which means they did not select two files to be uploaded
alert("Please press the browse button and pick a file.");
return false;
} else {
if(checkFileFormats == 0) {
//second check has failed, which means that oine of the files is neither jpg nor gif
alert("Please ensure you select only JPG or GIF images to upload");
return false;
} else {
return true;
}
}
}
}
</script>
To rename the files, you will have to do this after uploading.
The documentation makes it clear that this script does not have a saveas function, or a rename function.
Since you've got this script working I think it's worth sticking with it, so lets look at renaming the files using fso.
At the moment of uploading, do you know the client id?
The documentation makes it clear that this script does not have a saveas function, or a rename function.
Since you've got this script working I think it's worth sticking with it, so lets look at renaming the files using fso.
At the moment of uploading, do you know the client id?
here's the fuction for renaming the file
'renames a file using fso
Function fsoMoveFile(folderPath, fileName, newFileName)
Set fso = CreateObject("Scripting.Fi leSystemOb ject")
Set object = fso.GetFile(folderPath & "\" & fileName)
object.Move(folderPath & "\" & newFileName)
Set object = Nothing
Set fso = Nothing
fsoMoveFile = True
End Function
'renames a file using fso
Function fsoMoveFile(folderPath, fileName, newFileName)
Set fso = CreateObject("Scripting.Fi
Set object = fso.GetFile(folderPath & "\" & fileName)
object.Move(folderPath & "\" & newFileName)
Set object = Nothing
Set fso = Nothing
fsoMoveFile = True
End Function
When you call that function, which I think will be after the upload process has finished? , you need to pass 3 parameters - the folder path, the uploaded filemame, and your desired new filename.
to get your new filenames, first set out what it is currently, as uploaded.
uploadedFileName1 =
uploadedFileName2 =
'you could also add an additional check here, that the file suffix is either jpg or gif, if necessary
'if ( trim(lcase(right(uploadedF
'if ( trim(lcase(right(uploadedF
newFileName1 = client_id & "_head." & right(uploadedFileName1,3)
newFileName2 = client_id & "_body." & right(uploadedFileName2,3)
fsoMoveFile(folderPath, fileName1, newFileName1)
fsoMoveFile(folderPath, fileName2, newFileName2)
does that make sense?
once you get it working, you could also think about add some checks.
this code does not check that the file exists before attempting to rename it. in theory you wouldn't need to, you've just uploaded it so you know it's there, but still ...
this code also does not check that the new filename does not already exist, which could possibly occur if you load an image for the same client twice. if that is likely to ever happen, let me know and I'll help you add 2 extra steps using fso - fileExists and deleteFile - which effectively turn the rename function into an overwrite.
how did you go with this?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Definitley took a new approach but you assistance was great!
okay, good luck with the website