功能說明:
1) 帶進(jìn)度條
2)支持多文件批量上傳
3)支持不同格式批量上傳,且分類存放文件
3)如果配合ASPJPEG可以批量全自動(dòng)上傳相片
需要注意:Session("KzUpFileName") 用于記錄上傳后文件路徑
===先來看下flash部分的源碼======fileUpload.fla文件(flash 8 的格式)
// KzUploader Ver 2.0
// 程序:[GRKZ]sean
//加載.net組件
import flash.net.FileReference;
import flash.net.FileReferenceList;
//初始化 - 當(dāng)沒有選擇文件的時(shí)候,“上傳”按鈕不可用
uploadButn.enabled = false;
status_txt.text = " KzUploader Ver 2.0 \n提示: \n 點(diǎn)擊“瀏覽”按鈕,選擇你要上傳的文件. \n 程序設(shè)計(jì): [GRKZ]sean ";
//創(chuàng)建一個(gè)文件資源列表
var fileRefList:FileReferenceList = new FileReferenceList();
var totalBytes:Number = 0;
var uploadedBytes:Number = 0;
var uploadedBytes2:Array;
var filesCompleted:Number = 0;
var totalFiles:Number = 0;
var ExtArray:Array = new Array(".gif", ".jpg", ".bmp", ".png", ".swf", ".fla", ".cer", ".doc", ".xls", ".txt", ".pdf", ".rar", ".zip", ".mp3", ".wmv", ".rm", ".mp4", ".wma", ".mid", ".avi");
var OldPath;
//創(chuàng)建文件監(jiān)聽
var fileRefListener:Object = new Object();
_root.progressBar.visible = false;
//進(jìn)度條控制
function reDrawPB(pb, xCor, yCor) {
_root.destroyObject(pb);
_root.createObject("ProgressBar", pb, 0);
_root.progressBar.move(xCor, yCor);
_root.progressBar.label = "上傳進(jìn)度: %3%% ";
}
//選擇文件,"顯示當(dāng)前選擇文件信息"
fileRefListener.onSelect = function(fileRefList:FileReferenceList):Void {
// 允許上傳
uploadButn.enabled = true;
reDrawPB("progressBar", 272.0, 43.0);
status_txt.text = "當(dāng)前選擇文件為: \n";
status_txt.vPosition = status_txt.maxVPosition;
var list:Array = fileRefList.fileList;
var fileRef:FileReference;
totalBytes = 0;
for (var i:Number = 0; i<list.length; i++) {
fileRef = list[i];
totalBytes += fileRef.size;
status_txt.text += fileRef.name+'\n';
if (CheckExt(fileRef.name, ExtArray) == false) {
status_txt.text += '文件 '+fileRef.name+' 格式不符合上傳要求 \n';
uploadButn.enabled = false;
}
status_txt.vPosition = status_txt.maxVPosition;
}
status_txt.text += list.length+" 個(gè)文件上傳大小: ";
status_txt.text += GetSizeType(totalBytes);
status_txt.vPosition = status_txt.maxVPosition;
};
//上傳狀態(tài),"沒有選擇上傳文件"
fileRefListener.onCancel = function(fileRef:FileReference):Void {
uploadButn.enabled = false;
status_txt.text = "沒有選擇上傳文件. \n";
status_txt.vPosition = status_txt.maxVPosition;
};
//上傳狀態(tài),"正在上傳..."
fileRefListener.onOpen = function(fileRef:FileReference):Void {
status_txt.text += "正在上傳 "+fileRef.name+" 請(qǐng)稍等...\n";
status_txt.vPosition = status_txt.maxVPosition;
};
//上傳進(jìn)度條
fileRefListener.onProgress = function(fileRef:FileReference, bytesLoaded:Number, bytesTotal:Number):Void {
progressBar.mode = "manual";
var temp:Number = bytesLoaded-uploadedBytes2[fileRef.name];
uploadedBytes2[fileRef.name] = bytesLoaded;
uploadedBytes += temp;
progressBar.setProgress(uploadedBytes, totalBytes);
txtUploaded.text = GetSizeType(uploadedBytes);
txtTotal.text = GetSizeType(totalBytes);
};
//上傳狀態(tài),"上傳完成."
fileRefListener.onComplete = function(fileRef:FileReference):Void {
status_txt.text += fileRef.name+" 上傳完成.\n";
status_txt.vPosition = status_txt.maxVPosition;
filesCompleted++;
status_txt.text += filesCompleted+" / "+totalFiles+" 個(gè)文件.\n";
status_txt.vPosition = status_txt.maxVPosition;
if (filesCompleted == totalFiles) {
FinishedUpload();
}
};
// 異常錯(cuò)誤處理機(jī)制
fileRefListener.onHTTPError = function(fileRef:FileReference):Void {
status_txt.text += "保存文件 "+fileRef.name+" 時(shí)發(fā)生錯(cuò)誤.\n";
status_txt.vPosition = status_txt.maxVPosition;
};
fileRefListener.onIOError = function(fileRef:FileReference):Void {
status_txt.text += "保存文件 "+fileRef.name+" 時(shí)發(fā)生錯(cuò)誤. \n";
status_txt.vPosition = status_txt.maxVPosition;
};
fileRefListener.onSecurityError = function(fileRef:FileReference, errorString:Error):Void {
status_txt.text += "保存 "+fileRef.name+" 發(fā)生數(shù)據(jù)錯(cuò)誤. \n 錯(cuò)誤原因: "+errorString+"\n";
status_txt.vPosition = status_txt.maxVPosition;
};
//****************************************************************************************//
//添加監(jiān)聽
fileRefList.addListener(fileRefListener);
//瀏覽按鈕
browseButn.clickHandler = function() {
//*.gif;*.jpg;*.bmp;*.png;*.swf;*.cer;*.doc;*.xls;*.txt;*.rar;*.zip;*.mp3;*.wmv;*.rm;*.mp4;*.wma;*.mid;*.avi
fileRefList.browse([{description:"圖片格式(*.gif;*.jpg;*.bmp;*.png)", extension:"*.gif;*.jpg;*.bmp;*.png"}, {description:"音樂格式(*.mp3;*.wma;*.mid)", extension:"*.mp3;*.wma;*.mid"}, {description:"視頻格式(*.wmv;*.rm;*.mp4;*.avi)", extension:"*.wmv;*.rm;*.mp4;*.avi"}, {description:"動(dòng)畫格式(*.swf;*.fla)", extension:"*.swf;*.fla"}, {description:"文檔格式(*.cer;*.doc;*.xls;*.txt;*.pdf)", extension:"*.cer;*.doc;*.xls;*.txt;*.pdf"}, {description:"壓縮文件(*.rar;*.zip)", extension:"*.rar;*.zip"}]);
};
//上傳按鈕
uploadButn.clickHandler = function() {
var list:Array = fileRefList.fileList;
var fileRef:FileReference;
if (uploadButn.label == "上 傳") {
browseButn.enabled = false;
uploadButn.label = "取 消";
status_txt.text = "開始上傳:"+'\n';
status_txt.vPosition = status_txt.maxVPosition;
totalFiles = list.length;
filesCompleted = 0;
uploadedBytes = 0;
uploadedBytes2 = [];
txtOf.text = "/";
for (var i:Number = 0; i<list.length; i++) {
fileRef = list[i];
status_txt.text += "逐步上傳 "+fileRef.name+'\n';
status_txt.vPosition = status_txt.maxVPosition;
fileRef.addListener(fileRefListener);
uploadedBytes2[fileRef.name] = 0;
if (uploadPage != undefined) {
fileRef.upload(uploadPage);
}
//發(fā)送數(shù)據(jù)
}
} else {
status_txt.text += "已經(jīng)取消上傳."+'\n';
status_txt.vPosition = status_txt.maxVPosition;
for (var i:Number = 0; i<list.length; i++) {
fileRef = list[i];
fileRef.cancel();
}
uploadButn.label = "上 傳";
browseButn.enabled = true;
}
};
// 上傳完畢
function FinishedUpload() {
uploadButn.enabled = false;
uploadButn.label = "上 傳";
browseButn.enabled = true;
System.useCodepage = true;
var FilePathLoad = new LoadVars();
FilePathLoad.onLoad = function(success) {
if (success) {
status_txt.text += '-----保存文件路徑------\n';
var my_str:String = FilePathLoad.FilePath;
var my_array:Array = my_str.split(",");
for (var i = 0; i<my_array.length; i++) {
status_txt.text += my_array[i]+'\n';
}
status_txt.vPosition = status_txt.maxVPosition;
if (completeFunction != undefined) {
getURL('javascript:'+completeFunction+'(\''+my_str+'\');');
}
}
};
FilePathLoad.load(uploadPage+"?whatdo=readfilepath");
}
// 文件大小轉(zhuǎn)換函數(shù)
function GetSizeType(size:Number) {
if (size<1024) {
return int(size*100)/100+" bytes";
}
if (size<1048576) {
return int((size/1024)*100)/100+"KB";
}
if (size<1073741824) {
return int((size/1048576)*100)/100+"MB";
}
return int((size/1073741824)*100)/100+"GB";
}
function CheckExt(str, arr) {
str = str.toLowerCase();
long = str.length-4;
item = str.substr(long, 4);
HavExt = false;
for (i=0; i<arr.length; i++) {
if (arr[i] == item) {
HavExt = true;
break;
} else {
HavExt = false;
}
}
return HavExt;
}
下面是ASP部分代碼==kzUpload.asp
<%
'酷站批量上傳類 KzUpload Ver 2.0
'程序:[GRKZ]sean
'最后一次修改:2007-12-17
'需要注意:Session("KzUpFileName") 用于記錄上傳后文件路徑
Class Cls_KzUpload
'------------------------
Dim Form,File
Dim AllowExt_ '允許上傳類型(白名單)
Dim NoAllowExt_ '不允許上傳類型(黑名單)
Private oUpFileStream '上傳的數(shù)據(jù)流
Private isErr_ '錯(cuò)誤的代碼,0或true表示無錯(cuò)
Private ErrMessage_ '錯(cuò)誤的字符串信息
Private isGetData_ '指示是否已執(zhí)行過GETDATA過程
Private UpFileName_ '上傳保存文件名
'-------------------------
'類的屬性
Public Property Get Version
Version="KzUpload Ver 2.0"
End Property
Public Property Get isErr
isErr=isErr_
End Property
Public Property Get ErrMessage
ErrMessage=ErrMessage_
End Property
Public Property Get AllowExt
AllowExt=AllowExt_
End Property
Public Property Let AllowExt(Value)
AllowExt_=LCase(Value)
End Property
Public Property Get NoAllowExt
NoAllowExt=NoAllowExt_
End Property
Public Property Let NoAllowExt(Value)
NoAllowExt_=LCase(Value)
End Property
Public Property Get UpFileName
UpFileName = UpFileName_ '返回文件路徑
End Property
'----------------------------------------------------------------
'類實(shí)現(xiàn)代碼
'初始化類
Private Sub Class_Initialize
isErr_ = 0
NoAllowExt="" '用;號(hào)分開,如果黑名單為空,則判斷白名單
NoAllowExt=LCase(NoAllowExt)
AllowExt="gif;jpg;bmp;png;swf;fla;cer;doc;xls;txt;pdf;rar;zip;mid;mp3;mp4;wma;wmv;rm;avi"
'白名單,可以在這里預(yù)設(shè)可上傳的文件類型,以文件的后綴名來判斷,不分大小寫,每個(gè)后綴名用;號(hào)分開
AllowExt=LCase(AllowExt)
isGetData_=false
End Sub
'類結(jié)束
Private Sub Class_Terminate
on error Resume Next
'清除變量及對(duì)像
Form.RemoveAll
Set Form = Nothing
File.RemoveAll
Set File = Nothing
oUpFileStream.Close
Set oUpFileStream = Nothing
End Sub
'分析上傳的數(shù)據(jù)
Public Sub GetData (MaxSize)
'定義變量
on error Resume Next
if isGetData_=false then
Dim RequestBinDate,sSpace,bCrLf,sInfo,iInfoStart,iInfoEnd,tStream,iStart,oFileInfo
Dim sFormValue,sFileName
Dim iFindStart,iFindEnd
Dim iFormStart,iFormEnd,sFormName
'代碼開始
If Request.TotalBytes < 1 Then '如果沒有數(shù)據(jù)上傳
isErr_ = 1
ErrMessage_="沒有數(shù)據(jù)上傳"
Exit Sub
End If
If MaxSize > 0 Then '如果限制大小
If Request.TotalBytes > MaxSize Then
isErr_ = 2 '如果上傳的數(shù)據(jù)超出限制大小
ErrMessage_="上傳的數(shù)據(jù)超出限制大小"
Exit Sub
End If
End If
Set Form = Server.CreateObject ("Scripting.Dictionary")
Form.CompareMode = 1
Set File = Server.CreateObject ("Scripting.Dictionary")
File.CompareMode = 1
Set tStream = Server.CreateObject ("ADODB.Stream")
Set oUpFileStream = Server.CreateObject ("ADODB.Stream")
oUpFileStream.Type = 1
oUpFileStream.Mode = 3
oUpFileStream.Open
oUpFileStream.Write Request.BinaryRead (Request.TotalBytes)
oUpFileStream.Position = 0
RequestBinDate = oUpFileStream.Read
iFormEnd = oUpFileStream.Size
bCrLf = ChrB (13) & ChrB (10)
'取得每個(gè)項(xiàng)目之間的分隔符
sSpace = MidB (RequestBinDate,1, InStrB (1,RequestBinDate,bCrLf)-1)
iStart = LenB(sSpace)
iFormStart = iStart+2
'分解項(xiàng)目
Do
iInfoEnd = InStrB (iFormStart,RequestBinDate,bCrLf & bCrLf)+3
tStream.Type = 1
tStream.Mode = 3
tStream.Open
oUpFileStream.Position = iFormStart
oUpFileStream.CopyTo tStream,iInfoEnd-iFormStart
tStream.Position = 0
tStream.Type = 2
tStream.CharSet = "gb2312"
sInfo = tStream.ReadText
'取得表單項(xiàng)目名稱
iFormStart = InStrB (iInfoEnd,RequestBinDate,sSpace)-1
iFindStart = InStr (22,sInfo,"name=""",1)+6
iFindEnd = InStr (iFindStart,sInfo,"""",1)
sFormName = Mid (sinfo,iFindStart,iFindEnd-iFindStart)
'如果是文件
If InStr (45,sInfo,"filename=""",1) > 0 Then
Set oFileInfo = new cls_KzFileInfo
'取得文件屬性
iFindStart = InStr (iFindEnd,sInfo,"filename=""",1)+10
iFindEnd = InStr (iFindStart,sInfo,""""&vbCrLf,1)
sFileName = Mid (sinfo,iFindStart,iFindEnd-iFindStart)
oFileInfo.FileName = GetFileName(sFileName)
oFileInfo.FilePath = GetFilePath(sFileName)
oFileInfo.FileExt = GetFileExt(sFileName)
iFindStart = InStr (iFindEnd,sInfo,"Content-Type: ",1)+14
iFindEnd = InStr (iFindStart,sInfo,vbCr)
oFileInfo.FileMIME = Mid(sinfo,iFindStart,iFindEnd-iFindStart)
oFileInfo.FileStart = iInfoEnd
oFileInfo.FileSize = iFormStart -iInfoEnd -2
oFileInfo.FormName = sFormName
file.add sFormName,oFileInfo
else
'如果是表單項(xiàng)目
tStream.Close
tStream.Type = 1
tStream.Mode = 3
tStream.Open
oUpFileStream.Position = iInfoEnd
oUpFileStream.CopyTo tStream,iFormStart-iInfoEnd-2
tStream.Position = 0
tStream.Type = 2
tStream.CharSet = "gb2312"
sFormValue = tStream.ReadText
If Form.Exists (sFormName) Then
Form (sFormName) = Form (sFormName) & ", " & sFormValue
else
Form.Add sFormName,sFormValue
End If
End If
tStream.Close
iFormStart = iFormStart+iStart+2
'如果到文件尾了就退出
Loop Until (iFormStart+2) >= iFormEnd
RequestBinDate = ""
Set tStream = Nothing
isGetData_=true
end if
End Sub
'保存到文件,自動(dòng)覆蓋已存在的同名文件
Public Function SaveToFile(Item,Path)
SaveToFile=SaveToFileEx(Item,Path,True)
End Function
'保存到文件,自動(dòng)設(shè)置文件名
Public Function AutoSave(Item,Path)
AutoSave=SaveToFileEx(Item,Path,false)
End Function
'保存到文件,OVER為真時(shí),自動(dòng)覆蓋已存在的同名文件,否則自動(dòng)把文件改名保存
Private Function SaveToFileEx(Item,Path,Over)
Path=CreatePath(Path) '創(chuàng)建文件夾
Dim oFileStream
Dim tmpPath
Dim nohack '防黑緩沖
On Error Resume Next
isErr_=0
Set oFileStream = CreateObject ("ADODB.Stream")
oFileStream.Type = 1
oFileStream.Mode = 3
oFileStream.Open
oUpFileStream.Position = File(Item).FileStart
oUpFileStream.CopyTo oFileStream,File(Item).FileSize
nohack=split(path,".") '重要修改,防止黑客二進(jìn)制"01"斷名!!!
tmpPath=nohack(0)&"."&nohack(ubound(nohack)) '重要修改,防止黑客二進(jìn)制"01"斷名!!!
if Over then
if isAllowExt(GetFileExt(tmpPath)) then
oFileStream.SaveToFile tmpPath,2
Else
isErr_=3
ErrMessage_="該后綴名的文件不允許上傳!"
End if
Else
If isAllowExt(File(Item).FileExt) then
dim NewFileName
do
Err.Clear()
NewFileName = GetNewFileName()&"."&File(Item).FileExt
nohack=split(Path&NewFileName,".") '重要修改,防止黑客二進(jìn)制"01"斷名!!!
tmpPath=nohack(0)&"."&nohack(ubound(nohack)) '重要修改,防止黑客二進(jìn)制"01"斷名??!!
oFileStream.SaveToFile tmpPath,2
loop Until Err.number<1
Else
isErr_=3
ErrMessage_="該后綴名的文件不允許上傳!"
End if
End if
oFileStream.Close
Set oFileStream = Nothing
if isErr_=3 then
SaveToFileEx=""
else
SaveToFileEx= UpFileName_ & GetFileName(tmpPath)
if Session("KzUpFileName")="" then
Session("KzUpFileName") = SaveToFileEx
else
Session("KzUpFileName") = Session("KzUpFileName") & "," & SaveToFileEx
end if
end if
End Function
'取得文件數(shù)據(jù)
Public Function FileData(Item)
isErr_=0
if isAllowExt(File(Item).FileExt) then
oUpFileStream.Position = File(Item).FileStart
FileData = oUpFileStream.Read (File(Item).FileSize)
Else
isErr_=3
ErrMessage_="該后綴名的文件不允許上傳!"
FileData=""
End if
End Function
'取得文件路徑
Public function GetFilePath(FullPath)
If FullPath <> "" Then
GetFilePath = Left(FullPath,InStrRev(FullPath, "\"))
Else
GetFilePath = ""
End If
End function
'取得文件名
Public Function GetFileName(FullPath)
If FullPath <> "" Then
GetFileName = mid(FullPath,InStrRev(FullPath, "\")+1)
Else
GetFileName = ""
End If
End function
'取得文件的后綴名
Public Function GetFileExt(FullPath)
If FullPath <> "" Then
GetFileExt = LCase(Mid(FullPath,InStrRev(FullPath, ".")+1))
Else
GetFileExt = ""
End If
End function
'取得一個(gè)不重復(fù)的序號(hào)
Public Function GetNewFileName()
dim ranNum
dim dtNow
dtNow=Now()
Randomize
ranNum=int(90000*rnd)+10000
GetNewFileName=year(dtNow) & right("0" & month(dtNow),2) & right("0" & day(dtNow),2) & right("0" & hour(dtNow),2) & right("0" & minute(dtNow),2) & right("0" & second(dtNow),2) & ranNum
End Function
Public Function isAllowExt(Ext)
if NoAllowExt="" then
isAllowExt=cbool(InStr(1,";"&AllowExt&";",LCase(";"&Ext&";")))
else
isAllowExt=not CBool(InStr(1,";"&NoAllowExt&";",LCase(";"&Ext&";")))
end if
End Function
Private Function CreatePath(formPath)
Dim objFSO
Dim uploadpath
uploadpath = Year(Now) & "_" & Month(Now) '以年月創(chuàng)建上傳文件夾
UpFileName_ = formPath & uploadpath & "/"
On Error Resume Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(Server.MapPath(formPath & uploadpath)) = False Then
objFSO.CreateFolder Server.MapPath(formPath & uploadpath)
End If
CreatePath = Server.MapPath(formPath & uploadpath) &"\"
Set objFSO = Nothing
End Function
End Class
'----------------------------------------------------------------------------------------------------
'文件屬性類
Class cls_KzFileInfo
Dim FormName,FileName,FilePath,FileSize,FileMIME,FileStart,FileExt
End Class
%>
===上傳接收文件=kzuping.asp
<!--#include virtual="/edit/kzuploader/kzupload.asp" -->
<%
Server.ScriptTimeout = 300
Response.CacheControl = "no-cache"
Session.TimeOut = 60
if request("whatdo")="readfilepath" then
Response.Write "FilePath="&session("KzUpFileName")
Session("KzUpFileName") = ""
else
dim upfile,formPath,formName,oFile,FileName,FileExt,ExtTmp,i
dim Ext(5,1)
Ext(0,0) = "gif;jpg;bmp;png;" '圖片格式
Ext(0,1) = "image"
Ext(1,0) = "mp3;wma;mid;" '音樂格式
Ext(1,1) = "media"
Ext(2,0) = "wmv;rm;mp4;avi;" '視頻格式
Ext(2,1) = "media"
Ext(3,0) = "swf;fla;" '動(dòng)畫格式
Ext(3,1) = "flash"
Ext(4,0) = "cer;doc;xls;txt;pdf;" '文檔格式
Ext(4,1) = "file"
Ext(5,0) = "rar;zip;" '壓縮格式
Ext(5,1) = "file"
ExtTmp = "file"
set upfile = new Cls_KzUpload
upfile.GetData (10*1024*1024) '取得上傳數(shù)據(jù),限制最大上傳10M
if upfile.isErr then '如果出錯(cuò)
call Err.Raise(vbObjectError, " KzUploader Ver 2.0 ","上傳失敗:" & upfile.ErrMessage)
else
for each formName in upfile.file
set oFile=upfile.file(formname)
FileExt = right(oFile.FileName,3)
do while i =< 5
if instr(";"&Ext(i,0),right(FileExt,3))>0 then
ExtTmp = Ext(i,1)
exit do
end if
i = i + 1
loop
upfile.AutoSave formname,"/upfiles/"&ExtTmp&"/"
if upfile.iserr then
call Err.Raise(vbObjectError, " KzUploader Ver 2.0 ","上傳失?。? & upfile.ErrMessage)
else
'存入數(shù)據(jù)庫
'-----
end if
set oFile = nothing
next
end if
set upfile=nothing '刪除此對(duì)象
end if
%>
===上傳文件fileupload.asp====
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>upfile</title>
</head>
<body>
<form id="form1" enctype="multipart/form-data" method="POST">
<div>
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0"
width="550" height="100" id="fileUpload" align="middle">
<param name="allowScriptAccess" value="sameDomain" />
<param name="movie" value="fileUpload.swf" />
<param name="quality" value="high" />
<param name="wmode" value="transparent">
<PARAM NAME=FlashVars VALUE='uploadPage=kzuping.asp&completeFunction=UploadComplete'>
<embed src="fileUpload.swf"
FlashVars='uploadPage=kzuping.asp&completeFunction=UploadComplete'
quality="high" wmode="transparent" width="550" height="100"
name="fileUpload" align="middle" allowScriptAccess="sameDomain"
type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer" />
</object>
<script type="text/javascript" language="javascript">
function UploadComplete(str){
str = str.replace(",","\n");
alert("上傳文件分別保存為\n"+str);
}
</script>
</div>
</form>
</body>
</html>