你好,我用webuploader.html5only.min.js实现批量图片上传,我该怎么在action中获取上传的那些文件呢?

html-css015

你好,我用webuploader.html5only.min.js实现批量图片上传,我该怎么在action中获取上传的那些文件呢?,第1张

1.1 分片、并发

分片与并发结合,将一个大文件分割成多块,并发上传,极大地提高大文件的上传速度。

当网络问题导致传输错误时,只需要重传出错分片,而不是整个文件。另外分片传输能够更加实时的跟踪上传进度。

1.2 预览、压缩

支持常用图片格式jpg,jpeg,gif,bmp,png预览与压缩,节省网络数据传输。

解析jpeg中的meta信息,对于各种orientation做了正确的处理,同时压缩后上传保留图片的所有原始meta数据。

1.3 多途径添加文件

支持文件多选,类型过滤,拖拽(文件&文件夹),图片粘贴功能。

粘贴功能主要体现在当有图片数据在剪切板中时(截屏工具如QQ(Ctrl + ALT + A), 网页中右击图片点击复制),Ctrl + V便可添加此图片文件。

1.4 HTML5 &FLASH

兼容主流浏览器,接口一致,实现了两套运行时支持,用户无需关心内部用了什么内核。

同时Flash部分没有做任何UI相关的工作,方便不关心flash的用户扩展和自定义业务需求。

1.5 MD5秒传

当文件体积大、量比较多时,支持上传前做文件md5值验证,一致则可直接跳过。

如果服务端与前端统一修改算法,取段md5,可大大提升验证性能,耗时在20ms左右。

1.6 易扩展、可拆分

采用可拆分机制, 将各个功能独立成了小组件,可自由搭配。

采用AMD规范组织代码,清晰明了,方便高级玩家扩展。

2、引入资源

2.1 下载包内容

├── Uploader.swf // SWF文件,当使用Flash运行时需要引入。

├── webuploader.js // 完全版本。

├── webuploader.min.js // min版本

├── webuploader.flashonly.js // 只有Flash实现的版本。

├── webuploader.flashonly.min.js // min版本

├── webuploader.html5only.js // 只有Html5实现的版本。

├── webuploader.html5only.min.js // min版本

├── webuploader.withoutimage.js // 去除图片处理的版本,包括HTML5和FLASH.

└── webuploader.withoutimage.min.js // min版本

2.2 或者直接使用由staticfile提供的cdn版本,或者下载Git项目包。

// SWF文件,当使用Flash运行时需要引入。

├── http://cdn.staticfile.org/webuploader/0.1.0/Uploader.swf

// 完全版本。

├── http://cdn.staticfile.org/webuploader/0.1.0/webuploader.js

├── http://cdn.staticfile.org/webuploader/0.1.0/webuploader.min.js

// 只有Flash实现的版本。

├── http://cdn.staticfile.org/webuploader/0.1.0/webuploader.flashonly.js

├── http://cdn.staticfile.org/webuploader/0.1.0/webuploader.flashonly.min.js

// 只有Html5实现的版本。

├── http://cdn.staticfile.org/webuploader/0.1.0/webuploader.html5only.js

├── http://cdn.staticfile.org/webuploader/0.1.0/webuploader.html5only.min.js

// 去除图片处理的版本,包括HTML5和FLASH.

├── http://cdn.staticfile.org/webuploader/0.1.0/webuploader.withoutimage.js

└── http://cdn.staticfile.org/webuploader/0.1.0/webuploader.withoutimage.min.js

2.3 DIY打包

WebUploader文件打包借助了Grunt工具来实现

2.3.1 环境依赖

1.git命令行工具

2.node &npm命令行工具

3.grunt (npm install grunt-cli -g)

2.3.2 编译代码

1.克隆 webuploader git仓库,git clone https://github.com/fex-team/webuploader.git。

2.安装node依赖,npm install。

3.执行grunt dist,此动作会在dist目录下面创建合并版本的js, 包括通过uglify压缩的min版本。

2.3.3 配置

打开webuploader仓库根目录下面的Gruntfile.js文件, 代码合并有buildtask来完成。找到build配置项。

Gruntfile.js已经配置了一个自定义合并的demo. 打包只支持HTML5的版本

// 自己配置的实例

// glob语法。

custom: {

preset: "custom",

cwd: "src",

src: [

'widgets/**/*.js',

'runtime/html5/**/*.js' ],

dest: "dist/webuploader.custom.js"

}

3、angular指令——<web-uploader>

3.1 指令功能

添加一个上传文件按钮,可以自行配置上传文件的类型和过滤规则,且在弹出的模态框中进行操作,支持连续上传,分类选择上传

3.2 使用说明

这里只是使用说明,可能会加一些注意事项,具体参数或者变量说明请参看后面

3.2.1 页面添加一个指令

<web-uploader class="btn btn-info" type="image" accept="accept">uploader</web-uploader>

3.2.2 配置上传类型和过滤规则

上传类型

type有四种类型,分别为

image:图片

video:音视频

flash:flash

file:办公文档,压缩文件等等

过滤规则

accept有四个对象属性,属性中包含标题、允许文件后缀、允许的mimetype

3.2.3 指令中绑定弹出模态框的事件

web-uploader这个指令中其实只做了一件事,给元素本身绑定弹出模态框的事件,具体上传文件是在模态框中完成的

3.2.4 初始化uploader类,配置相关属性

在模态框控制器中用到了$timeout

$timeout(function(){

//这里是上传配置代码

},0)

因为配置uploader时需要事先准备好dom元素,angular打开模态框是异步而JavaScript是单线程,所以实际上在执行模态框控制器中的代码时,模态框并没有打开,也就是dom并没有加载完成,这会导致WebUploader报a.runningtime is not a function...的错误

3.3 指令详细说明

3.3.1 父级controller中的配置

.controller('myCtrl',['$scope', '$modal', function($scope, $modal){

//配置允许上传的类型 图片/音视频/flash/文件

$scope.accept = {

//图片

image: {

title : 'Images',//标题

extensions : 'gif,jpg,jpeg,bmp,png,ico',//允许上传文件的后缀

mimeTypes : 'image/*'//允许的mimetype

},

//音视频

video: {

title : 'Videos',

extensions : 'wmv,asf,asx,rm,rmvb,ram,avi,mpg,dat,mp4,mpeg,divx,m4v,mov,qt,flv,f4v,mp3,wav,aac,m4a,wma,ra,3gp,3g2,dv,vob,mkv,ts',

mimeTypes : 'video/*,audio/*'

},

//flash

flash: {

title : 'Flashs',

extensions : 'swf,fla',

mimeTypes : 'application/x-shockwave-flash'

},

//办公文档,压缩文件等等

file: {

title : 'Files',

extensions : 'zip,rar,ppt,pptx,doc,docx,xls,xlsx,pdf',

mimeTypes : 'application/zip,application/x-rar-compressed,application/vnd.ms-powerpoint,application/vnd.openxmlformats- officedocument.presentationml.presentation,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms- excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/pdf'

}

}

}])

3.3.2 指令web-uploader

.directive('webUploader', ['$modal', function($modal){

return{

restrict: 'AE',

scope: {

accept: '=accept'

},

link: function($scope, $element, $attr){

$element.bind('click',function(){

var modalInstance = $modal.open({

controller: 'modalCtrl',

templateUrl: 'template/webuploader.tpl.html',

size:'lg',

resolve: {

items: function(){

return {

accept: $scope.accept,

type: $attr.type

}

}

}

})

modalInstance.result.then(function(returnStatus){

console.log(returnStatus)

},function(){

console.log('Modal dismissed at: ' + new Date())

})

})

}

}

}])

<%@LANGUAGE="VBSCRIPT" CODEPAGE="936"%><% function GetFilePath(FullPath,str) If FullPath <>"" Then GetFilePath = left(FullPath,InStrRev(FullPath, str)) Else GetFilePath = "" End If End function %><% class clsUp '文件上传类 '------------------------ Dim Form,File Dim AllowExt_ '允许上传类型(白名单) Dim NoAllowExt_ '不允许上传类型(黑名单) Private oUpFileStream '上传的数据流 Private isErr_ '错误的代码,0或true表示无错 Private ErrMessage_ '错误的字符串信息 Private isGetData_ '指示是否已执行过GETDATA过程 '------------------------------------------------------------------ '类的属性 Public Property Get Version Version="上传类声明" End Property Public Property Get isErr '错误的代码,0或true表示无错 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 '---------------------------------------------------------------- '类实现代码 '初始化类 Private Sub Class_Initialize isErr_ = 0 NoAllowExt="" '黑名单,可以在这里预设不可上传的文件类型,以文件的后缀名来判断,不分大小写,每个每缀名用号分开,如果黑名单为空,则判断白名单 NoAllowExt=LCase(NoAllowExt) AllowExt="" '白名单,可以在这里预设可上传的文件类型,以文件的后缀名来判断,不分大小写,每个后缀名用号分开 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 clsFileInfo '取得文件属性 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) On Error Resume Next Dim oFileStream Dim tmpPath Dim nohack '防黑缓冲 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 Path=GetFilePath(Path) if isAllowExt(File(Item).FileExt) then do Err.Clear() nohack=split(Path&GetNewFileName()&"."&File(Item).FileExt,".") '重要修改,防止黑客二进制"01"断名!!! tmpPath=nohack(0)&"."&nohack(ubound(nohack)) '重要修改,防止黑客二进制"01"断名!!! oFileStream.SaveToFile tmpPath loop Until Err.number<1 oFileStream.SaveToFile Path Else isErr_=3 ErrMessage_="该后缀名的文件不允许上传!" End if End if oFileStream.Close Set oFileStream = Nothing if isErr_=3 then SaveToFileEx="" else SaveToFileEx=GetFileName(tmpPath) 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() 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 End Class PS:下面还有一部分代码!最后需要整合一起!

Web Uploader 项目,符合你的要求。

1、引入资源

使用Web Uploader文件上传需要引入三种资源:JS, CSS, SWF。

<!--引入CSS-->

<link rel="stylesheet" type="text/css" href="webuploader文件夹/webuploader.css">

<!--引入JS-->

<script type="text/javascript" src="webuploader文件夹/webuploader.js"></script>

<!--SWF在初始化的时候指定,在后面将展示-->

2、Html

首先需要准备一个按钮,和一个用来存放添加的文件信息列表的容器。

<!--dom结构部分-->

<div id="uploader-demo">

    <!--用来存放item-->

    <div id="fileList" class="uploader-list"></div>

    <div id="filePicker">选择图片</div>

</div>

3、Javascript

创建Web Uploader实例

// 初始化Web Uploader

var uploader = WebUploader.create({

    // 选完文件后,是否自动上传。

    auto: true,

    // swf文件路径

    swf: BASE_URL + '/js/Uploader.swf',

    // 文件接收服务端。

    server: 'http://webuploader.duapp.com/server/fileupload.php',

    // 选择文件的按钮。可选。

    // 内部根据当前运行是创建,可能是input元素,也可能是flash.

    pick: '#filePicker',

    // 只允许选择图片文件。

    accept: {

        title: 'Images',

        extensions: 'gif,jpg,jpeg,bmp,png',

        mimeTypes: 'image/*'

    }

})

监听fileQueued事件,通过uploader.makeThumb来创建图片预览图。

PS: 这里得到的是Data URL数据,IE6、IE7不支持直接预览。可以借助FLASH或者服务端来完成预览。

// 当有文件添加进来的时候

uploader.on( 'fileQueued', function( file ) {

    var $li = $(

            '<div id="' + file.id + '" class="file-item thumbnail">' +

                '<img>' +

                '<div class="info">' + file.name + '</div>' +

            '</div>'

            ),

        $img = $li.find('img')

    // $list为容器jQuery实例

    $list.append( $li )

    // 创建缩略图

    // 如果为非图片文件,可以不用调用此方法。

    // thumbnailWidth x thumbnailHeight 为 100 x 100

    uploader.makeThumb( file, function( error, src ) {

        if ( error ) {

            $img.replaceWith('<span>不能预览</span>')

            return

        }

        $img.attr( 'src', src )

    }, thumbnailWidth, thumbnailHeight )

})

然后剩下的就是上传状态提示了,当文件上传过程中, 上传成功,上传失败,上传完成都分别对应uploadProgress, uploadSuccess, uploadError, uploadComplete事件。

// 文件上传过程中创建进度条实时显示。

uploader.on( 'uploadProgress', function( file, percentage ) {

    var $li = $( '#'+file.id ),

        $percent = $li.find('.progress span')

    // 避免重复创建

    if ( !$percent.length ) {

        $percent = $('<p class="progress"><span></span></p>')

                .appendTo( $li )

                .find('span')

    }

    $percent.css( 'width', percentage * 100 + '%' )

})

// 文件上传成功,给item添加成功class, 用样式标记上传成功。

uploader.on( 'uploadSuccess', function( file ) {

    $( '#'+file.id ).addClass('upload-state-done')

})

// 文件上传失败,显示上传出错。

uploader.on( 'uploadError', function( file ) {

    var $li = $( '#'+file.id ),

        $error = $li.find('div.error')

    // 避免重复创建

    if ( !$error.length ) {

        $error = $('<div class="error"></div>').appendTo( $li )

    }

    $error.text('上传失败')

})

// 完成上传完了,成功或者失败,先删除进度条。

uploader.on( 'uploadComplete', function( file ) {

    $( '#'+file.id ).find('.progress').remove()

})

更多细节,请查看js源码。