However, some cases only need to pass a few files, and the file volume is not too large, in this case, the use of components is a bit of a nut to kill chicken feeling, through the HTML <input type= "file" > form can realize the required functions, the key is the processing of background receiving procedures.
PHP processing upload is very convenient, upload file information through the server automatically processed into the $_files array, developers only need to use the built-in processing function simple operation can be. ASP developers are not so lucky, the official does not provide a direct processing method, the need for developers to design their own, this time need developers to understand the enctype= "multipart/form-data" form of the processing, IIS Enctype= " Multipart/form-data "form submitted data stored as binary data, returned to the developer in binary format, developers need to use LenB, MidB byte processing function to analyze the uploaded content, the client sent the specific form data format, you can understand the next HTTP Knowledge of RFC1867 protocol transfer format.
Here are my methods for handling multiple file uploads, including PHP and ASP two versions.
Php:website_dirroot represents the site root directory:
Copy Code code as follows:
<?php
/*
* Class: File Upload Class
* AUTHOR:51JS.COM-ZMM
* date:2011.1.20
* email:304924248@qq.com
* blog:http://www.cnblogs.com/cnzmm/
*/
Class Upload {
Public $up _ext=array (), $up _max=5210, $up _dir;
Private $up _name, $up _rename=true, $up _num=0, $up _files=array (), $up _ret=array ();
function __construct ($name, $ext =array (), $rename =true) {
if (!empty ($name)) {
$this->up_name = $name;
!empty ($ext) && $this->up_ext = $ext;
$this->up_rename = $rename;
$this->up_dir = Website_dirroot.
$GLOBALS [' Cfg_upload_path '];
$this->initupload ();
} else {
Exit (' Upload file domain name is empty, initialization failed! ');
}
}
Private Function Initupload () {
if (Is_array ($_files[$this->up_name])) {
$up _arr = count ($_files[$this->up_name]);
$up _all = count ($_files[$this->up_name], 1);
$up _cnt = ($up _all-$up _arr)/$up _arr;
for ($i = 0; $i < $up _cnt; $i + +) {
if ($_files[$this->up_name][' error '] [$i]!= 4) {
$this->up_files[] = Array (
' Tmp_name ' => $_files[$this->up_name][' tmp_name ' [$i],
' Name ' => $_files[$this->up_name][' name ' [$i],
' Type ' => $_files[$this->up_name][' type ' [$i],
' Size ' => $_files[$this->up_name][' size ' [$i],
' Error ' => $_files[$this->up_name][' ERROR ' [$i]
);
}
}
$this->up_num = count ($this->up_files);
} else {
if (Isset ($_files[$this->up_name])) {
$this->up_files = Array (
' Tmp_name ' => $_files[$this->up_name][' tmp_name '],
' Name ' => $_files[$this->up_name][' name '],
' Type ' => $_files[$this->up_name][' type '],
' Size ' => $_files[$this->up_name][' size '],
' Error ' => $_files[$this->up_name][' ERROR ']
);
$this->up_num = 1;
} else {
Exit (' not find the file that needs upload! ');
}
}
$this->chkupload ();
}
Private Function Chkupload () {
if (Empty ($this->up_ext)) {
$up _mime = Array (' image/wbmp ', ' image/bmp ', ' image/gif ', ' image/pjpeg ', ' image/x-png ');
foreach ($this->up_files as $up _file) {
$up _ALLW = false;
foreach ($up _mime as $mime) {
if ($up _file[' type '] = = $mime) {
$up _ALLW = true; Break
}
}
! $up _allw && exit (' not allowed to upload '. $up _file[' type ']. ' File in a format! ');
if ($up _file[' size ']/1024 > $this->up_max) {
Exit (' Do not allow uploading of files larger than '. $this->up_max. ' K! ');
}
}
} else {
foreach ($this->up_files as $up _file) {
$up _ext = end (Explode ('. ', $up _file[' name '));
$up _ALLW = false;
foreach ($this->up_ext as $ext) {
if ($up _ext = = $ext) {
$up _ALLW = true; Break
}
}
$up _allw && exit (' not allowed to upload. ') $up _ext. ' Format Files! ');
if ($up _file[' size ']/1024 > $this->up_max) {
Exit (' Do not allow uploading of files larger than '. $this->up_max. ' K! ');
}
}
}
$this->uploading ();
}
Private function uploading () {
if (IO::D ircreate ($this->up_dir)) {
if (chmod ($this->up_dir, 0777)) {
if (!empty ($this->up_files)) {
foreach ($this->up_files as $up _file) {
if (Is_uploaded_file ($up _file[' Tmp_name ')) {
$file _name = $up _file[' name '];
if ($this->up_rename) {
$file _ext = end (Explode ('. ', $file _name));
$file _rnd = substr (MD5 (UNIQID ()), Mt_rand (0, 26), 6);
$file _name = Date (' Ymdhis '). ' _ '. $file _rnd. '. $file _ext;
}
$file _name = $this->up_dir. '/'. $file _name;
if (Move_uploaded_file ($up _file[' tmp_name '], $file _name)) {
$this->up_ret[] = str_replace (Website_dirroot, ', $file _name);
} else {
Exit (' File upload failed! ');
}
}
}
}
} else {
Exit (' Write permission not turned on! ');
}
} else {
Exit (' Upload directory creation failed! ');
}
}
Public Function Getupload () {
return empty ($this->up_ret)? False: $this->up_ret;
}
function __destruct () {}
}
?>
Asp:
Copy Code code as follows:
<%
Class Multiupload
REM public-variant
Public Form, isfinished
Private Bvbcrlf, Bseparate, fpassed, FormData, FileType, FileSize, FolderPath, _
Frename, Fimgonly, ItemCount, chunksize, Btime, Serrors, Sauthor, sversion
Private Itemstart (), Itemlength (), Datastart (), datalength (), ItemName (), ItemData (), Extenarr (), Httparr ()
REM class-initialize
Private Sub Class_Initialize
Call Initvariant
Server.ScriptTimeout = 1800
Set Form = Server.CreateObject ("Scripting.Dictionary")
Sauthor = "51JS.COM-ZMM"
Sversion = "Multiupload Class 3.0"
End Sub
REM class-attributes
Public Property Let Allowtype (ByVal stype)
Dim regEx
Set regEx = New RegExp
Regex.pattern = "^ (\w+\|) *\w+$ "
Regex.global = False
Regex.ignorecase = True
If regex.test (stype) Then fileType = "|" & Ucase (stype) & "|"
Set regEx = Nothing
End Property
Public Property Let MaxSize (ByVal ssize)
If IsNumeric (ssize) Then fileSize = CDBL (FormatNumber (CCur), 2)
End Property
Public Property Let Savefolder (ByVal sfolder)
FolderPath = Sfolder
End Property
Public Property Let commonpassed (ByVal bcheck)
fpassed = bcheck
End Property
Public Property Let Filerenamed (ByVal brename)
Frename = Brename
End Property
Public Property Let Fileisallimg (ByVal bonly)
Fimgonly = bonly
End Property
Public Property Get Savefolder
Savefolder = FolderPath
End Property
Public Property Get Filerenamed
filerenamed = Frename
End Property
Public Property Get Fileisallimg
Fileisallimg = fimgonly
End Property
Public Property Get Errmessage
Errmessage = Serrors
End Property
Public Property Get Clsauthor
Clsauthor = Sauthor
End Property
Public Property Get Clsversion
Clsversion = Sversion
End Property
REM Class-methods
Private Function Initvariant
isfinished = False
Bvbcrlf = Strtobyte (VbCrlf & VbCrlf)
Bseparate = Strtobyte (String (29, "-"))
fpassed = False
FileType = "*"
FileSize = "*"
Frename = True
Fimgonly = True
ItemCount = 0
chunksize = 1024 * 128
Btime = Now
Serrors = ""
End Function
Public Function Getuploaddata
Dim curread:curread = 0
Dim Datalen:datalen = request.totalbytes
Dim appname:appname = "PROGRESS" & Iptonum (GETCLIENTIPADDR)
Dim streamtmp
Set streamtmp = Server.CreateObject ("ADODB. Stream ")
Streamtmp.type = 1
Streamtmp.open
Do While Curread < Datalen
Dim Partlen:partlen = chunksize
If Partlen + curread > datalen Then partlen = Datalen-curread
Streamtmp.write Request.BinaryRead (Partlen)
Curread = Curread + Partlen
Letprogress AppName, Array (Curread, Datalen, DateDiff ("s", Btime, now), FolderPath)
Loop
streamtmp.position = 0
FormData = Streamtmp.read (datalen)
Streamtmp.close
Set streamtmp = Nothing
Call Itemposition
End Function
Private Function letprogress (byVal sname, ByVal Varr)
Application.value (sname) = Join (Varr, "|")
End Function
Private Function delprogress
Application.Contents.Remove ("PROGRESS" & Iptonum (GETCLIENTIPADDR))
End Function
Private Function itemposition
Dim IStart, Ilength:istart = 1
Do Until InStrB (IStart, formData, bseparate) = 0
IStart = InStrB (IStart, FormData, bseparate) + LenB (bseparate) + 14
Ilength = InStrB (IStart, FormData, bseparate)-iStart-2
If Abs (IStart + 2-lenb (formData)) > 2 Then
ReDim Preserve Itemstart (itemCount)
ReDim Preserve itemlength (itemCount)
Itemstart (itemCount) = IStart
Itemlength (itemCount) = Ilength
ItemCount = ItemCount + 1
End If
Loop
Call Fillitemvalue
End Function
Private Function Fillitemvalue
Dim Datapart, Binfor
Dim Istart:istart = 1
Dim icount:icount = 0
Dim Icheck:icheck = strtobyte ("filename")
For i = 0 to ItemCount-1
ReDim Preserve ItemName (icount)
ReDim Preserve ItemData (icount)
ReDim Preserve Extenarr (icount)
ReDim Preserve Httparr (icount)
ReDim Preserve Datastart (icount)
ReDim Preserve datalength (icount)
Datapart = MidB (FormData, Itemstart (i), itemlength (i))
IStart = InStrB (1, Datapart, ChrB (34)) + 1
Ilength = InStrB (IStart, Datapart, ChrB)-IStart
ItemName (icount) = Getitemname (MidB (Datapart, IStart, Ilength))
IStart = InStrB (1, Datapart, BVBCRLF) + 4
Ilength = LenB (datapart)-IStart + 1
If InStrB (1, Datapart, Icheck) > 0 Then
Binfor = MidB (Datapart, 1, iStart-5)
Extenarr (icount) = Fileextenname (binfor)
Httparr (icount) = Gethttpcontent (binfor)
If IsNothing (Extenarr (icount)) Then
ItemData (icount) = ""
Datastart (icount) = ""
Datalength (icount) = ""
Else
If Mid (FolderPath, Len (FolderPath)-1) = "/" Then
If Frename Then
ItemData (icount) = FolderPath & Getrandomname (6) & Extenarr (icount)
Else
ItemData (icount) = FolderPath & Getclientname (binfor) & Extenarr (icount)
End If
Else
If Frename Then
ItemData (icount) = FolderPath & "/" & Getrandomname (6) & Extenarr (icount)
Else
ItemData (icount) = FolderPath & "/" & Getclientname (binfor) & Extenarr (icount)
End If
End If
Datastart (icount) = Itemstart (i) + iStart-2
Datalength (icount) = Ilength
End If
Else
Extenarr (icount) = ""
Httparr (icount) = ""
ItemData (icount) = Bytetostr (MidB (Datapart, IStart, Ilength))
Datastart (icount) = ""
Datalength (icount) = ""
End If
icount = icount + 1
Next
Call Itemtocoll
End Function
Private Function getitemname (byVal bname)
Getitemname = Bytetostr (bname)
End Function
Private Function Itemtocoll
For i = 0 to ItemCount-1
If not form.exists (ItemName (i)) Then
Form.add ItemName (i), ItemData (i)
End If
Next
End Function
Private Function fileextenname (ByVal binfor)
Dim Pcontent, RegEx
Pcontent = Getclientpath (binfor)
If isnothing (pcontent) Then
Fileextenname = ""
Else
Set regEx = New RegExp
Regex.pattern = "^.+" (\.[ ^\.] +)$"
Regex.global = False
Regex.ignorecase = True
Fileextenname = Regex.Replace (pcontent, "$")
Set regEx = Nothing
End If
End Function
Private Function gethttpcontent (ByVal binfor)
Dim Sinfor, RegEx
Sinfor = Bytetostr (binfor)
Set regEx = New RegExp
Regex.pattern = "^[\s\s]+content-type: ([\s\s]+) $"
Regex.global = False
Regex.ignorecase = True
Gethttpcontent = Trim (Regex.Replace (sinfor, "$")
Set regEx = Nothing
End Function
Private Function getrandomname (ByVal slen)
Dim regEx, Stemp, arrfields, n:n = 0
Set regEx = New RegExp
Regex.pattern = "[^\d]+"
Regex.global = True
Regex.ignorecase = True
Stemp = Regex.Replace (now, "") & "-"
Set regEx = Nothing
Arrfields = Array ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", _
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", _
"K", "L", "M", "N", "O", "P", "Q", "R", "s", "T", _
"U", "V", "w", "X", "Y", "Z", "A", "B", "C", "D", _
"E", "F", "G", "H", "I", "J", "K", "L", "M", "N", _
"O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", _
"Y", "Z")
Randomize
Do While n < Slen
Stemp = stemp & CStr (Arrfields (Rnd))
n = n + 1
Loop
Getrandomname = stemp
End Function
Private Function getclientname (ByVal binfor)
Dim Pcontent, RegEx
Pcontent = Getclientpath (binfor)
If isnothing (pcontent) Then
Getclientname = ""
Else
Set regEx = New RegExp
Regex.pattern = "^.*\\" ([^\.] *)[^\\]+$"
Regex.global = False
Regex.ignorecase = True
Getclientname = Regex.Replace (pcontent, "$")
Set regEx = Nothing
End If
End Function
Private Function Getclientpath (ByVal binfor)
Dim sinfor, Pstart, Plength, pcontent
Sinfor = Bytetostr (binfor)
Pstart = INSTR (1, sinfor, "Filename=" & Chr (34)) + 10
Plength = InStr (Pstart, Sinfor, Chr)-Pstart
Pcontent = Mid (Sinfor, Pstart, Plength)
Getclientpath = Pcontent
End Function
Public Function Saveuploadfile
Dim isvalidate
Dim FilePath, Ostreamget, Ostreamput
Isvalidate = fpassed and Checkfile
If isvalidate Then
For i = 0 to ItemCount-1
If not IsNothing (Datastart (i)) and not IsNothing (datalength (i)) Then
If datalength (i) = 0 Then
ItemData (i) = ""
Else
FilePath = Server.MapPath (ItemData (i))
If CreateFolder ("|", ParentFolder (FilePath)) Then
Set ostreamget = Server.CreateObject ("ADODB. Stream ")
Ostreamget.type = 1
Ostreamget.mode = 3
Ostreamget.open
Ostreamget.write FormData
Ostreamget.position = Datastart (i)
Set ostreamput = Server.CreateObject ("ADODB. Stream ")
Ostreamput.type = 1
Ostreamput.mode = 3
Ostreamput.open
Ostreamput.write Ostreamget.read (datalength (i))
Ostreamput.savetofile FilePath, 2
Ostreamget.close
Set Ostreamget = Nothing
Ostreamput.close
Set Ostreamput = Nothing
End If
End If
End If
Next
isfinished = True
Else
isfinished = False
End If
End Function
Private Function Checkfile
Dim Oboolean:oboolean = True
Checkfile = Oboolean and Checktype and Checksize
End Function
Private Function Checktype
Dim Oboolean:oboolean = True
If FileType = "*" Then
Oboolean = Oboolean and True
Else
For i = 0 to ItemCount-1
If not IsNothing (Extenarr (i)) Then
If InStr (1, fileType, "|" & Ucase (Mid (Extenarr (i), 2)) & "|") > 0 Then
If fimgonly Then
Dim Sallow:sallow = "| Gif| Pjpeg| X-png| Bmp| "
Dim Acheck:acheck = Split (UCase (Httparr (i)), "/"
Dim Icheck:icheck = "|" & Acheck (Ubound (Acheck)) & "|"
If InStr (1, Sallow, Icheck, 1) > 0 Then
Oboolean = Oboolean and True
Else
serrors = serrors & Form [& ItemName (i) &] file format Error! \ n ' & _
"Supported formats are:" & Replace (Mid fileType, 2, Len (FileType)-1), "|", "") & "\ n"
Oboolean = Oboolean and False
End If
Else
Oboolean = Oboolean and True
End If
Else
serrors = serrors & Form [& ItemName (i) &] file format Error! \ n ' & _
"Supported formats are:" & Replace (Mid fileType, 2, Len (FileType)-1), "|", "") & "\ n"
Oboolean = Oboolean and False
End If
End If
Next
End If
Checktype = Oboolean
End Function
Private Function Checksize
Dim Oboolean:oboolean = True
If fileSize = "*" Then
Oboolean = Oboolean and True
Else
For i = 0 to ItemCount-1
If not IsNothing (datalength (i)) Then
Dim tmpsize:tmpsize = CDBL (FormatNumber (CCur (datalength (i))/1024, 2)
If tmpsize <= fileSize Then
Oboolean = Oboolean and True
Else
Serrors = serrors & "form [& ItemName (i) &"] File Size ("& Tmpsize &" KB) out of range! \ n ' & _
"Support size Range: <=" & fileSize & "kb\n\n"
Oboolean = Oboolean and False
End If
End If
Next
End If
Checksize = Oboolean
End Function
Private Function CreateFolder (ByVal sline, ByVal spath)
Dim oFSO
Set oFSO = Server.CreateObject ("Scripting.FileSystemObject")
If not ofso.folderexists (spath) Then
Dim regEx
Set regEx = New RegExp
Regex.pattern = "^ (. *) \ ([^\\]*) $"
Regex.global = False
Regex.ignorecase = True
sline = sline & Regex.Replace (spath, "$") & "|"
spath = Regex.Replace (spath, "$")
If CreateFolder (sline, spath) Then CreateFolder = True
Set regEx = Nothing
Else
If sline = "|" Then
CreateFolder = True
Else
Dim stemp:stemp = Mid (sline, 2, Len (sline)-2)
If InStrRev (stemp, "|") = 0 Then
sline = "|"
spath = spath & "\" & Stemp
Else
Dim Folder:folder = Mid (Stemp, InStrRev (stemp, "|") + 1)
sline = "|" & Mid (Stemp, 1, InStrRev (stemp, "|")-1) & "|"
spath = spath & "\" & Folder
End If
Ofso.createfolder spath
If CreateFolder (sline, spath) Then CreateFolder = True
End If
End If
Set oFSO = Nothing
End Function
Private Function ParentFolder (ByVal spath)
Dim regEx
Set regEx = New RegExp
Regex.pattern = "^ (. *) \\[^\\]*$"
Regex.global = True
Regex.ignorecase = True
ParentFolder = Regex.Replace (spath, "$")
Set regEx = Nothing
End Function
Private Function isnothing (ByVal sVar)
IsNothing = CBool (SVar = Empty)
End Function
Private Function strpadleft (byVal stext, ByVal slen, ByVal Schar)
Dim stemp:stemp = stext
Do While Len (stemp) < Slen:stemp = Schar & Stemp:loop
Strpadleft = stemp
End Function
Private Function strtobyte (ByVal stext)
For i = 1 to Len (stext)
Strtobyte = strtobyte & ChrB (ASC (Mid (Stext, I, 1))
Next
End Function
Private Function bytetostr (ByVal sByte)
Dim Ostream
Set ostream = Server.CreateObject ("ADODB. Stream ")
Ostream.type = 2
Ostream.mode = 3
Ostream.open
Ostream.writetext SByte
ostream.position = 0
Ostream.charset = "gb2312"
Ostream.position = 2
Bytetostr = Ostream.readtext
Ostream.close
Set ostream = Nothing
End Function
Private Function getclientipaddr
If IsNothing (Getservervar ("Http_x_forwarded_for")) Then
GETCLIENTIPADDR = Getservervar ("REMOTE_ADDR")
Else
GETCLIENTIPADDR = Getservervar ("Http_x_forwarded_for")
End If
End Function
Private Function Getservervar (ByVal stext)
Getservervar = Request.ServerVariables (stext)
End Function
Private Function iptonum (ByVal sIp)
Dim sip_1, sip_2, Sip_3, Sip_4
If IsNumeric (Left (sIp, 2)) Then
Sip_1 = Left (sip, InStr (SIP, ".")-1)
SIP = Mid (sip, INSTR (SIP, ".") + 1)
Sip_2 = Left (sip, InStr (SIP, ".")-1)
SIP = Mid (sip, INSTR (SIP, ".") + 1)
Sip_3 = Left (sip, InStr (SIP, ".")-1)
Sip_4 = Mid (SIP, INSTR (SIP, ".") + 1)
End If
Iptonum = CInt (sip_1) * 256 * 256 * 256 + CINT (sip_2) * 256 * 256 + CINT (sip_3) * 256 + CINT (sip_4)-1
End Function
REM class-terminate
Private Sub Class_Terminate
Call Delprogress
Form.removeall
Set Form = Nothing
End Sub
End Class
%>