常州网络公司首页 >>> WEB编程 >> ASP

FLASH+ASP批量上传类 KzUpload Ver 2.0 源文件

发布时间:2010-3-11 15:02:08   浏览次数:11617

最近要搞一个指上传文件的代码,网上找了很久,只有FLASH+ASP批量上传类 KzUpload Ver 2.0这个版本最好,有源码,可以上传不同格式的文件。
可这个只有代码,没有FLA源码文件,让我很郁闷。

经过研究,根据FLASH的代码,自己搞出了个FLA源文件,且测试能正常使用。这里代码下载。

下面很多把所有代码贴出来。

下面是FLASH代码
// KzUploader Ver 2.0
// 程序:[GRKZ]sean
//加载.net组件
import flash.net.FileReference;
import flash.net.FileReferenceList;
//初始化 - 当没有选择文件的时候,“上传”按钮不可用
uploadButn.enabled = false;
status_txt.text = "提示: \n    点击“浏览”按钮,选择你要上传的文件. \n";

uploadButn.label = "上 传";
browseButn.label = "浏 览";
//创建一个文件资源列表
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;
//创建文件监听
var fileRefListener:Object = new Object();
_root.progressBar.visible = false;
//进度条控制
function reDrawPB(pb, xCor, yCor) {
_root.destroyObject(pb);
_root.createObject("ProgressBar", pb, 0);
_root.progressBar.move(xCor, yCor);
_root.progressBar.label = "上传进度: %3%% ";
}
//选择文件,"显示当前选择文件信息"
fileRefListener.onSelect = function(fileRefList:FileReferenceList):Void {
// 允许上传
uploadButn.enabled = true;
reDrawPB("progressBar", 345.0,55.0);
status_txt.text = "当前选择文件为: \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+" 个文件上传大小: ";
status_txt.text += GetSizeType(totalBytes);
status_txt.vPosition = status_txt.maxVPosition;
};
//上传状态,"没有选择上传文件"
fileRefListener.onCancel = function(fileRef:FileReference):Void {
uploadButn.enabled = false;
status_txt.text = "没有选择上传文件. \n";
status_txt.vPosition = status_txt.maxVPosition;
};
//上传状态,"正在上传..."
fileRefListener.onOpen = function(fileRef:FileReference):Void {
status_txt.text += "正在上传 "+fileRef.name+" 请稍等...\n";
status_txt.vPosition = status_txt.maxVPosition;
};
//上传进度条
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);
};
//上传状态,"上传完成."
fileRefListener.onComplete = function(fileRef:FileReference):Void {
status_txt.text += fileRef.name+" 上传完成.\n";
status_txt.vPosition = status_txt.maxVPosition;
filesCompleted++;
status_txt.text += filesCompleted+" / "+totalFiles+" 个文件.\n";
status_txt.vPosition = status_txt.maxVPosition;
if (filesCompleted == totalFiles) {
   FinishedUpload();
}
};
// 异常错误处理机制
fileRefListener.onHTTPError = function(fileRef:FileReference):Void {
status_txt.text += "保存文件 "+fileRef.name+" 时发生错误.HTTPError\n";
status_txt.vPosition = status_txt.maxVPosition;
};
fileRefListener.onIOError = function(fileRef:FileReference):Void {
status_txt.text += "保存文件 "+fileRef.name+" 时发生错误.IOError\n";
status_txt.vPosition = status_txt.maxVPosition;
};
fileRefListener.onSecurityError = function(fileRef:FileReference, errorString:Error):Void {
status_txt.text += "保存 "+fileRef.name+" 发生数据错误. \n 错误原因: "+errorString+"\n";
status_txt.vPosition = status_txt.maxVPosition;
};
//****************************************************************************************//
//添加监听
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:"动画格式(*.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);
    }
    //发送数据     
   }
} else {
   status_txt.text += "已经取消上传."+'\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");
}
// 文件大小转换函数
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;
}

 

下面是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 '上传的数据流
Private isErr_ '错误的代码,0或true表示无错
Private ErrMessage_ '错误的字符串信息
Private isGetData_ '指示是否已执行过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
'----------------------------------------------------------------
'类实现代码

'初始化类
Private Sub Class_Initialize
isErr_ = 0
NoAllowExt="" '用;号分开,如果黑名单为空,则判断白名单
NoAllowExt=LCase(NoAllowExt)
AllowExt="gif;jpg;bmp;png;swf;fla;cer;doc;xls;txt;pdf;rar;zip;mid;mp3;mp4;wma;wmv;rm;avi"
'白名单,可以在这里预设可上传的文件类型,以文件的后缀名来判断,不分大小写,每个后缀名用;号分开
AllowExt=LCase(AllowExt)
isGetData_=false
End Sub

'类结束
Private Sub Class_Terminate
on error Resume Next
'清除变量及对像
Form.RemoveAll
Set Form = Nothing
File.RemoveAll
Set File = Nothing
oUpFileStream.Close
Set oUpFileStream = Nothing
End Sub

'分析上传的数据
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 '如果没有数据上传
isErr_ = 1
ErrMessage_="没有数据上传"
Exit Sub
End If
If MaxSize > 0 Then '如果限制大小
If Request.TotalBytes > MaxSize Then
isErr_ = 2 '如果上传的数据超出限制大小
ErrMessage_="上传的数据超出限制大小"
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)
'取得每个项目之间的分隔符
sSpace = MidB (RequestBinDate,1, InStrB (1,RequestBinDate,bCrLf)-1)
iStart = LenB(sSpace)
iFormStart = iStart+2
'分解项目
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
'取得表单项目名称
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
'如果是表单项目
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

'保存到文件,自动覆盖已存在的同名文件
Public Function SaveToFile(Item,Path)
SaveToFile=SaveToFileEx(Item,Path,True)
End Function

'保存到文件,自动设置文件名
Public Function AutoSave(Item,Path)
AutoSave=SaveToFileEx(Item,Path,false)
End Function

'保存到文件,OVER为真时,自动覆盖已存在的同名文件,否则自动把文件改名保存
Private Function SaveToFileEx(Item,Path,Over)
Path=CreatePath(Path) '创建文件夹
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,".") '重要修改,防止黑客二进制"01"断名!!!
tmpPath=nohack(0)&"."&nohack(ubound(nohack)) '重要修改,防止黑客二进制"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 = File(Item).FileName '源名保存
'GetNewFileName()&"."&File(Item).FileExt '新的文件名保存
nohack=split(Path&NewFileName,".") '重要修改,防止黑客二进制"01"断名!!!
tmpPath=nohack(0)&"."&nohack(ubound(nohack)) '重要修改,防止黑客二进制"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

'取得文件数据
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

'取得一个不重复的序号
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) '以年月创建上传文件夹
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) &"\" '以时间新建目录
CreatePath = Server.MapPath(formPath) &"\"  '指定目录
Set objFSO = Nothing
End Function

End Class

'----------------------------------------------------------------------------------------------------

'文件属性类
Class cls_KzFileInfo
Dim FormName,FileName,FilePath,FileSize,FileMIME,FileStart,FileExt
End Class

%>


下面是kzuping.asp

<!--#include file="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;" '动画格式
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) '取得上传数据,限制最大上传10M
if upfile.isErr then '如果出错
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&"/"
upfile.AutoSave formname,"../../uploadfile/"

if upfile.iserr then
call Err.Raise(vbObjectError, " KzUploader Ver 2.0 ","上传失败:" & upfile.ErrMessage)
else
'存入数据库
'-----

end if
set oFile = nothing
next

end if
set upfile=nothing '删除此对象

end if
%>


下面是fileupload.asp

<form id="formupfile" enctype="multipart/form-data" method="POST">
      <td><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
         codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" name="fileUpload"
         width="550" height="100" align="middle" id="fileUpload">
            <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></td></form>

 

以上代码,经过我适当的修改,直接拷到同一目录下就可以上传功能。红色部分是我修改过的,如果你要还原,可以自己修改。

最后提醒一下,这个批量上传,不能上传的文件名不能为中文。

怎么样?我这里提供的源文件不错吧?感觉不错,就点我一个广告,呵呵。。。

上一条:ASP随机产生一段字符串
下一条:无效使用 Null: 'replace'
首页 | 在线留言 | 网站地图

CopyRight ©2008-2014   糊涂蛋技术网    苏ICP备05013073号
站长:万创   QQ:54960248  E-mail:xlxcn#126.com