찾다
백엔드 개발PHP 튜토리얼php+flex打造多文件带进度超级上传_PHP

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

效果截图:

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으로 문의하세요.
PHP와 Python : 다른 패러다임이 설명되었습니다PHP와 Python : 다른 패러다임이 설명되었습니다Apr 18, 2025 am 12:26 AM

PHP는 주로 절차 적 프로그래밍이지만 객체 지향 프로그래밍 (OOP)도 지원합니다. Python은 OOP, 기능 및 절차 프로그래밍을 포함한 다양한 패러다임을 지원합니다. PHP는 웹 개발에 적합하며 Python은 데이터 분석 및 기계 학습과 같은 다양한 응용 프로그램에 적합합니다.

PHP와 Python : 그들의 역사에 깊은 다이빙PHP와 Python : 그들의 역사에 깊은 다이빙Apr 18, 2025 am 12:25 AM

PHP는 1994 년에 시작되었으며 Rasmuslerdorf에 의해 개발되었습니다. 원래 웹 사이트 방문자를 추적하는 데 사용되었으며 점차 서버 측 스크립팅 언어로 진화했으며 웹 개발에 널리 사용되었습니다. Python은 1980 년대 후반 Guidovan Rossum에 의해 개발되었으며 1991 년에 처음 출시되었습니다. 코드 가독성과 단순성을 강조하며 과학 컴퓨팅, 데이터 분석 및 기타 분야에 적합합니다.

PHP와 Python 중에서 선택 : 가이드PHP와 Python 중에서 선택 : 가이드Apr 18, 2025 am 12:24 AM

PHP는 웹 개발 및 빠른 프로토 타이핑에 적합하며 Python은 데이터 과학 및 기계 학습에 적합합니다. 1.PHP는 간단한 구문과 함께 동적 웹 개발에 사용되며 빠른 개발에 적합합니다. 2. Python은 간결한 구문을 가지고 있으며 여러 분야에 적합하며 강력한 라이브러리 생태계가 있습니다.

PHP 및 프레임 워크 : 언어 현대화PHP 및 프레임 워크 : 언어 현대화Apr 18, 2025 am 12:14 AM

PHP는 현대화 프로세스에서 많은 웹 사이트 및 응용 프로그램을 지원하고 프레임 워크를 통해 개발 요구에 적응하기 때문에 여전히 중요합니다. 1.PHP7은 성능을 향상시키고 새로운 기능을 소개합니다. 2. Laravel, Symfony 및 Codeigniter와 같은 현대 프레임 워크는 개발을 단순화하고 코드 품질을 향상시킵니다. 3. 성능 최적화 및 모범 사례는 응용 프로그램 효율성을 더욱 향상시킵니다.

PHP의 영향 : 웹 개발 및 그 이상PHP의 영향 : 웹 개발 및 그 이상Apr 18, 2025 am 12:10 AM

phphassignificallyimpactedwebdevelopmentandextendsbeyondit

스칼라 유형, 반환 유형, 노조 유형 및 무효 유형을 포함한 PHP 유형의 힌트 작업은 어떻게 작동합니까?스칼라 유형, 반환 유형, 노조 유형 및 무효 유형을 포함한 PHP 유형의 힌트 작업은 어떻게 작동합니까?Apr 17, 2025 am 12:25 AM

PHP 유형은 코드 품질과 가독성을 향상시키기위한 프롬프트입니다. 1) 스칼라 유형 팁 : PHP7.0이므로 int, float 등과 같은 기능 매개 변수에 기본 데이터 유형을 지정할 수 있습니다. 2) 반환 유형 프롬프트 : 기능 반환 값 유형의 일관성을 확인하십시오. 3) Union 유형 프롬프트 : PHP8.0이므로 기능 매개 변수 또는 반환 값에 여러 유형을 지정할 수 있습니다. 4) Nullable 유형 프롬프트 : NULL 값을 포함하고 널 값을 반환 할 수있는 기능을 포함 할 수 있습니다.

PHP는 객체 클로닝 (클론 키워드) 및 __clone 마법 방법을 어떻게 처리합니까?PHP는 객체 클로닝 (클론 키워드) 및 __clone 마법 방법을 어떻게 처리합니까?Apr 17, 2025 am 12:24 AM

PHP에서는 클론 키워드를 사용하여 객체 사본을 만들고 \ _ \ _ Clone Magic 메소드를 통해 클로닝 동작을 사용자 정의하십시오. 1. 복제 키워드를 사용하여 얕은 사본을 만들어 객체의 속성을 복제하지만 객체의 속성은 아닙니다. 2. \ _ \ _ 클론 방법은 얕은 복사 문제를 피하기 위해 중첩 된 물체를 깊이 복사 할 수 있습니다. 3. 복제의 순환 참조 및 성능 문제를 피하고 클로닝 작업을 최적화하여 효율성을 향상시키기 위해주의를 기울이십시오.

PHP vs. Python : 사용 사례 및 응용 프로그램PHP vs. Python : 사용 사례 및 응용 프로그램Apr 17, 2025 am 12:23 AM

PHP는 웹 개발 및 컨텐츠 관리 시스템에 적합하며 Python은 데이터 과학, 기계 학습 및 자동화 스크립트에 적합합니다. 1.PHP는 빠르고 확장 가능한 웹 사이트 및 응용 프로그램을 구축하는 데 잘 작동하며 WordPress와 같은 CMS에서 일반적으로 사용됩니다. 2. Python은 Numpy 및 Tensorflow와 같은 풍부한 라이브러리를 통해 데이터 과학 및 기계 학습 분야에서 뛰어난 공연을했습니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.