首页 后端开发 php教程 php+flex打造多文件带进度超级上传_PHP

php+flex打造多文件带进度超级上传_PHP

Jun 01, 2016 pm 12:21 PM

最近我们西西弗斯工作室(北京网站建设)要做一个文件上传的功能,要求是可以批量上传,并且是大影音文件,于是在网上找了相关的资料和开源项目,进行了一些简单的改造。

效果截图:

flex的源码是:

以下为引用的内容:



    <script>        import mx.events.*;<br>        import com.newmediateam.fileIO.*;<br>        import flash.events.*;<br>        import flash.media.*;<br>        import flash.net.*;<br>        import mx.containers.*;<br>        import mx.controls.*;<br>        import mx.core.*;<br>        import mx.events.*;<br>        import mx.styles.*;<br><br>        public var snd:SoundAsset;<br>        public var documentTypes:FileFilter;<br>        public var soundClass:Class;<br>        public var multiFileUpload:MultiFileUpload;<br>        public var uploadDestination:String = "upload.php";<br>        public var sndChannel:SoundChannel;<br>        public var filesToFilter:Array;<br><br>        public function uploadsfinished(event:Event) : void<br>        {<br>            sndChannel = snd.play();<br>            return;<br>        }// end function<br><br>    <br>        public function initApp() : void<br>        {<br>            var _loc_1:* = new URLVariables();<br>            _loc_1.path=this.parameters["file"];<br>            multiFileUpload = new MultiFileUpload(filesDG, browseBTN, clearButton, delButton, upload_btn, progressbar, uploadDestination, _loc_1, 1024000000, filesToFilter);<br>            multiFileUpload.addEventListener(Event.COMPLETE, uploadsfinished);<br>            return;<br>        }// end function<br><br>    ]]></script>
   
       
       
       
           
           
           
               
               
               
               
           

       

   
   

      大家可以看到_loc_1.path=this.parameters["file"]接收file参数,然后传入MultiFileUpload对象中,这个的意思是你可以通过页面来定义上传的目录.对于MultiFileUpload组件的源码如下:

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//

//    Multi-File Upload Component Ver 1.1

//

//  Copyright (C) 2006 Ryan Favro and New Media Team Inc.

//  This program is free software; you can redistribute it and/or

//  modify it under the terms of the GNU General Public License

//  as published by the Free Software Foundation; either version 2

//    of the License, or (at your option) any later version.

//    

//    This program is distributed in the hope that it will be useful,

//    but WITHOUT ANY WARRANTY; without even the implied warranty of

//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the

//    GNU General Public License for more details.

//    

//    You should have received a copy of the GNU General Public License

//    along with this program; if not, write to the Free Software

//    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

//

//    Any questions about this component can be directed to it's author Ryan Favro at ryanfavro@hotmail.com

//

//  To use this component create a new instance of this component and give it ten parameters

//

//    EXAMPLE:

//

//    multiFileUpload = new MultiFileUpload(

//          filesDG,           //

//          browseBTN,         //

//          clearButton,         //

//          delButton,         //

//          upload_btn,         //

//          progressbar,         //

//          "http://[Your Server Here]/MultiFileUpload/upload.cfm", //

//          postVariables,      //

//          350000,             //

//          filesToFilter     //

//           );

//

//

//

//    Enjoy!

//

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

package com.newmediateam.fileIO {

    // Imported Class Definitions

    import mx.controls.DataGrid;

    import mx.controls.Button;

    import mx.controls.ProgressBar;

    import mx.controls.ProgressBarMode;

    import mx.controls.dataGridClasses.*;

    import mx.controls.Alert;

    import mx.events.CollectionEvent;

    import mx.collections.ArrayCollection;

    import flash.events.*;

    import flash.net.FileReferenceList;

    import flash.net.FileFilter;

    import flash.net.FileReference;

    import flash.net.URLRequest;

    import flash.net.URLVariables;

    

    

    public class MultiFileUpload {

    

        

        

        //UI Vars

        private var _datagrid:DataGrid;

        private var _browsebutton:Button;

        private var _remselbutton:Button;

        private var _remallbutton:Button;

        private var _uploadbutton:Button;

        private var _progressbar:ProgressBar;

        private var _testButton:Button;

        //DataGrid Columns

        private var _nameColumn:DataGridColumn;

        private var _typeColumn:DataGridColumn;

        private var _sizeColumn:DataGridColumn;

        private var _creationDate:DataGridColumn;

        private var _modificationDate:DataGridColumn;

        private var _progressColumn:DataGridColumn;

        private var _columns:Array;

        

        //File Reference Vars

        [Bindable]

        private var _files:ArrayCollection;

        private var _fileref:FileReferenceList

        private var _file:FileReference;

        private var _uploadURL:URLRequest;

        private var  _totalbytes:Number;

        

        //File Filter vars

        private var _filefilter:Array;

        //config vars

        private var _url:String; // location of the file upload handler can be a relative path or FQDM

        private var _maxFileSize:Number; //bytes

        private var _variables:URLVariables; //variables to passed along to the file upload handler on the server.

        

        //Constructor    

        public function MultiFileUpload(

                                        dataGrid:DataGrid,

                                        browseButton:Button,

                                        removeAllButton:Button,

                                        removeSelectedButton:Button,

                                        uploadButton:Button,

                                        progressBar:ProgressBar,

                                        url:String,

                                        variables:URLVariables,

                                        maxFileSize:Number,

                                        filter:Array

                                        ){

            _datagrid = dataGrid;

            _browsebutton = browseButton;

            _remallbutton = removeAllButton;

            _remselbutton = removeSelectedButton;            

            _uploadbutton = uploadButton;

            _url = url;

            _progressbar = progressBar;

            _variables = variables;

            _maxFileSize = maxFileSize;

            _filefilter = filter;

            init();

        }

        

        //Initialize  Component

        private function init():void{

            

            // Setup File Array Collection and FileReference

            _files = new ArrayCollection();

            _fileref = new FileReferenceList;

            _file = new FileReference;

            

            // Set Up Total Byes Var

            _totalbytes = 0;

            

            // Add Event Listeners to UI

            _browsebutton.addEventListener(MouseEvent.CLICK, browseFiles);

            _uploadbutton.addEventListener(MouseEvent.CLICK,uploadFiles);

            _remallbutton.addEventListener(MouseEvent.CLICK,clearFileCue);

            _remselbutton.addEventListener(MouseEvent.CLICK,removeSelectedFileFromCue);

            _fileref.addEventListener(Event.SELECT, selectHandler);

            _files.addEventListener(CollectionEvent.COLLECTION_CHANGE,popDataGrid);

            

            // Set Up Progress Bar UI

            _progressbar.mode = "manual";

            _progressbar.label = "";

            

            // Set Up UI Buttons;

            _uploadbutton.enabled = false;

            _remselbutton.enabled = false;

            _remallbutton.enabled = false;

            

            

            // Set Up DataGrid UI

            _nameColumn = new DataGridColumn;

            _typeColumn = new DataGridColumn;

            _sizeColumn = new DataGridColumn;

                

            _nameColumn.dataField = "name";

            _nameColumn.headerText= "File";

            

            _typeColumn.dataField = "type";

            _typeColumn.headerText = "File Type";

            _typeColumn.width = 80;

            

            _sizeColumn.dataField = "size";

            _sizeColumn.headerText = "File Size";

            _sizeColumn.labelFunction = bytesToKilobytes as Function;

            _sizeColumn.width = 150;

            

            _columns = new Array(_nameColumn,_typeColumn,_sizeColumn);

            _datagrid.columns = _columns

            _datagrid.sortableColumns = false;

            _datagrid.dataProvider = _files;

            _datagrid.dragEnabled = true;

            _datagrid.dragMoveEnabled = true;

            _datagrid.dropEnabled = true;

            

            // Set Up URLRequest

            _uploadURL = new URLRequest;

            _uploadURL.url = _url;

            _uploadURL.method = "GET";  // this can also be set to "POST" depending on your needs

            

            _uploadURL.data = _variables;

            _uploadURL.contentType = "multipart/form-data";

            

            

        }

        

        /********************************************************

        *   PRIVATE METHODS                                     *

        ********************************************************/

        

        

        //Browse for files

        private function browseFiles(event:Event):void{        

                

                _fileref.browse(_filefilter);

                

            }

        //Upload File Cue

        private function uploadFiles(event:Event):void{

           

            if (_files.length > 0){

                _file = FileReference(_files.getItemAt(0));    

                _file.addEventListener(Event.OPEN, openHandler);

                _file.addEventListener(ProgressEvent.PROGRESS, progressHandler);

                _file.addEventListener(Event.COMPLETE, completeHandler);

                _file.addEventListener(SecurityErrorEvent.SECURITY_ERROR,securityErrorHandler);

                _file.addEventListener(HTTPStatusEvent.HTTP_STATUS,httpStatusHandler);

                _file.addEventListener(IOErrorEvent.IO_ERROR,ioErrorHandler);

                _file.upload(_uploadURL);

                 setupCancelButton(true);

            }

        }

        

        //Remove Selected File From Cue

        private function removeSelectedFileFromCue(event:Event):void{

           

            if (_datagrid.selectedIndex >= 0){

            _files.removeItemAt( _datagrid.selectedIndex);

            }

        }

         //Remove all files from the upload cue;

        private function clearFileCue(event:Event):void{

       

            _files.removeAll();

        }

        

        // Cancel Current File Upload

        private function cancelFileIO(event:Event):void{

            

            _file.cancel();

            setupCancelButton(false);

            checkCue();

            

        }    

    

       

        //label function for the datagird File Size Column

        private function bytesToKilobytes(data:Object,blank:Object):String {

            var kilobytes:String;

            kilobytes = String(Math.round(data.size/ 1024)) + ' kb';

            return kilobytes

        }

        

        

        // Feed the progress bar a meaningful label

        private function getByteCount():void{

            var i:int;

            _totalbytes = 0;

                for(i=0;i

                _totalbytes +=  _files[i].size;

                }

            _progressbar.label = "Total Files: "+  _files.length+ " Total Size: " + Math.round(_totalbytes/1024) + " kb"

        }        

        

        // Checks the files do not exceed maxFileSize | if _maxFileSize == 0 No File Limit Set

        private function checkFileSize(filesize:Number):Boolean{

      

            var r:Boolean = false;

                //if  filesize greater then _maxFileSize

                if (filesize > _maxFileSize){

                    r = false;

                    trace("false");

                    }else if (filesize

                    r = true;

                    trace("true");

                }

                

                if (_maxFileSize == 0){

                r = true;

                }

           

            return r;

        }

        

        // restores progress bar back to normal

        private function resetProgressBar():void{

        

                  _progressbar.label = "";

                 _progressbar.maximum = 0;

                 _progressbar.minimum = 0;

        }

        

        // reset form item elements

        private function resetForm():void{

            _uploadbutton.enabled = false;

            _uploadbutton.addEventListener(MouseEvent.CLICK,uploadFiles);

            _uploadbutton.label = "Upload";

            _progressbar.maximum = 0;

            _totalbytes = 0;

            _progressbar.label = "";

            _remselbutton.enabled = false;

            _remallbutton.enabled = false;

            _browsebutton.enabled = true;

        }

        

        // whenever the _files arraycollection changes this function is called to make sure the datagrid data jives

        private function popDataGrid(event:CollectionEvent):void{                

            getByteCount();

            checkCue();

        }

        

       // enable or disable upload and remove controls based on files in the cue;        

        private function checkCue():void{

             if (_files.length > 0){

                _uploadbutton.enabled = true;

                _remselbutton.enabled = true;

                _remallbutton.enabled = true;            

             }else{

                resetProgressBar();

                _uploadbutton.enabled = false;     

             }    

        }

        // toggle upload button label and function to trigger file uploading or upload cancelling

        private function setupCancelButton(x:Boolean):void{

            if (x == true){

                _uploadbutton.label = "Cancel";

                _browsebutton.enabled = false;

                _remselbutton.enabled = false;

                _remallbutton.enabled = false;

                _uploadbutton.addEventListener(MouseEvent.CLICK,cancelFileIO);        

            }else if (x == false){

                _uploadbutton.removeEventListener(MouseEvent.CLICK,cancelFileIO);

                 resetForm();

            }

        }

        

       /*********************************************************

       *  File IO Event Handlers                                *

       *********************************************************/

      

        //  called after user selected files form the browse dialouge box.

        private function selectHandler(event:Event):void {

            var i:int;

            var msg:String ="";

            var dl:Array = [];                          

                for (i=0;i

                    if (checkFileSize(event.currentTarget.fileList[i].size)){

                    _files.addItem(event.currentTarget.fileList[i]);

                    trace("under size " + event.currentTarget.fileList[i].size);

                    }  else {

                    dl.push(event.currentTarget.fileList[i]);

                    trace(event.currentTarget.fileList[i].name + " too large");

                    }

                }                

                if (dl.length > 0){

                    for (i=0;i

                    msg += String(dl[i].name + " is too large. \n");

                    }

                    mx.controls.Alert.show(msg + "Max File Size is: " + Math.round(_maxFileSize / 1024) + " kb","File Too Large",4,null).clipContent;

                }        

        }        

        

        // called after the file is opened before upload    

        private function openHandler(event:Event):void{

            trace('openHandler triggered');

            _files;

        }

        

        // called during the file upload of each file being uploaded | we use this to feed the progress bar its data

        private function progressHandler(event:ProgressEvent):void {        

            _progressbar.setProgress(event.bytesLoaded,event.bytesTotal);

            _progressbar.label = "Uploading " + Math.round(event.bytesLoaded / 1024) + " kb of " + Math.round(event.bytesTotal / 1024) + " kb " + (_files.length - 1) + " files remaining";

        }

        // called after a file has been successully uploaded | we use this as well to check if there are any files left to upload and how to handle it

        private function completeHandler(event:Event):void{

            //trace('completeHanderl triggered');

            _files.removeItemAt(0);

            if (_files.length > 0){

                _totalbytes = 0;

                uploadFiles(null);

            }else{

                setupCancelButton(false);

                 _progressbar.label = "Uploads Complete";

                 var uploadCompleted:Event = new Event(Event.COMPLETE);

                dispatchEvent(uploadCompleted);

            }

        }    

          

        // only called if there is an  error detected by flash player browsing or uploading a file   

        private function ioErrorHandler(event:IOErrorEvent):void{

            //trace('And IO Error has occured:' +  event);

            mx.controls.Alert.show(String(event),"ioError",0);

        }    

        // only called if a security error detected by flash player such as a sandbox violation

        private function securityErrorHandler(event:SecurityErrorEvent):void{

            //trace("securityErrorHandler: " + event);

            mx.controls.Alert.show(String(event),"Security Error",0);

        }

        

        //  This function its not required

        private function cancelHandler(event:Event):void{

            // cancel button has been clicked;

            trace('cancelled');

        }

        

        //  after a file upload is complete or attemted the server will return an http status code, code 200 means all is good anything else is bad.

        private function httpStatusHandler(event:HTTPStatusEvent):void {

        //        trace("httpStatusHandler: " + event);

            if (event.status != 200){

                mx.controls.Alert.show(String(event),"Error",0);

            }

        }

        

    }

}

上传工具了,非常好用,大家试试吧,有什么不懂的可以来沟通,我的Q376504340.

北京网站建设www.beijingjianzhan.com首发,转载请注明,谢谢.

感谢 xxfs 的投稿

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

在PHP API中说明JSON Web令牌(JWT)及其用例。 在PHP API中说明JSON Web令牌(JWT)及其用例。 Apr 05, 2025 am 12:04 AM

JWT是一种基于JSON的开放标准,用于在各方之间安全地传输信息,主要用于身份验证和信息交换。1.JWT由Header、Payload和Signature三部分组成。2.JWT的工作原理包括生成JWT、验证JWT和解析Payload三个步骤。3.在PHP中使用JWT进行身份验证时,可以生成和验证JWT,并在高级用法中包含用户角色和权限信息。4.常见错误包括签名验证失败、令牌过期和Payload过大,调试技巧包括使用调试工具和日志记录。5.性能优化和最佳实践包括使用合适的签名算法、合理设置有效期、

会话如何劫持工作,如何在PHP中减轻它? 会话如何劫持工作,如何在PHP中减轻它? Apr 06, 2025 am 12:02 AM

会话劫持可以通过以下步骤实现:1.获取会话ID,2.使用会话ID,3.保持会话活跃。在PHP中防范会话劫持的方法包括:1.使用session_regenerate_id()函数重新生成会话ID,2.通过数据库存储会话数据,3.确保所有会话数据通过HTTPS传输。

在PHPStorm中如何进行CLI模式的调试? 在PHPStorm中如何进行CLI模式的调试? Apr 01, 2025 pm 02:57 PM

在PHPStorm中如何进行CLI模式的调试?在使用PHPStorm进行开发时,有时我们需要在命令行界面(CLI)模式下调试PHP�...

描述扎实的原则及其如何应用于PHP的开发。 描述扎实的原则及其如何应用于PHP的开发。 Apr 03, 2025 am 12:04 AM

SOLID原则在PHP开发中的应用包括:1.单一职责原则(SRP):每个类只负责一个功能。2.开闭原则(OCP):通过扩展而非修改实现变化。3.里氏替换原则(LSP):子类可替换基类而不影响程序正确性。4.接口隔离原则(ISP):使用细粒度接口避免依赖不使用的方法。5.依赖倒置原则(DIP):高低层次模块都依赖于抽象,通过依赖注入实现。

如何在系统重启后自动设置unixsocket的权限? 如何在系统重启后自动设置unixsocket的权限? Mar 31, 2025 pm 11:54 PM

如何在系统重启后自动设置unixsocket的权限每次系统重启后,我们都需要执行以下命令来修改unixsocket的权限:sudo...

解释PHP中的晚期静态绑定(静态::)。 解释PHP中的晚期静态绑定(静态::)。 Apr 03, 2025 am 12:04 AM

静态绑定(static::)在PHP中实现晚期静态绑定(LSB),允许在静态上下文中引用调用类而非定义类。1)解析过程在运行时进行,2)在继承关系中向上查找调用类,3)可能带来性能开销。

框架安全功能:防止漏洞。 框架安全功能:防止漏洞。 Mar 28, 2025 pm 05:11 PM

文章讨论了框架中的基本安全功能,以防止漏洞,包括输入验证,身份验证和常规更新。

See all articles