0

我只是在开发一个 Flex 移动应用程序,需要显示一个图像的上传进度。

代码是:

protected function upload( ba:ByteArray, fileName:String = null ):void {
            if( fileName == null ) {                
                var now:Date = new Date();
                fileName = "IMG" + now.fullYear + now.month +now.day +
                    now.hours + now.minutes + now.seconds + ".jpg";
            }

            var loader:URLLoader    = new URLLoader();
            loader.dataFormat       = URLLoaderDataFormat.BINARY;

            var wrapper:URLRequestWrapper = new URLRequestWrapper(ba, fileName, null, params);
            wrapper.url = "http://www.the_url_to_upload.com/php_content/upload_image.php";

            loader.addEventListener( Event.COMPLETE,            completeImageHandler );
            loader.addEventListener( ProgressEvent.PROGRESS,    imageProgress);
            loader.addEventListener(IOErrorEvent.IO_ERROR,      errorImageUploading );
            loader.load(wrapper.request);
        }
        private function imageProgress(evt:ProgressEvent):void {
            var pcent:Number=Math.floor(evt.bytesLoaded/evt.bytesTotal*100);
            label_upload.text = pcent+"%";
        }

我有一个名为“label_upload”的标签,它应该显示文件上传时的进度百分比。

事实是一切正常,但进度事件不会改变任何东西。始终显示 0%。

我猜不出我的错。

谢谢。

4

1 回答 1

1

Flash 不提供上传文件的进度事件 - 仅下载。

如果您需要进度事件,则必须将文件拆分为多个部分并一次上传每个部分;手动更新进度消息以响应每个部分的完成事件。例如:

//assume file to upload stored as ByteArray called "ba"

//setup counters
currentChunk = 0;
totalChunks = Math.ceil(ba.length/CHUNK_SIZE);
//listener
loader.addEventListener(Event.COMPLETE, completeHandler);

此代码将发送一个块:

function sendChunk():void
{
    const CHUNK_SIZE:int = 4096;
    var request:URLRequest = new URLRequest(destinationUrl);
    request.method = URLRequestMethod.POST;
    request.contentType = "application/octet-stream";
    request.data = new ByteArray();
    var chunkSize:uint = Math.min(CHUNK_SIZE, ba.bytesAvailable);
    ba.readBytes(request.data as ByteArray, 0, chunkSize);
    loader.load(request);
}

CHUNK_SIZE 是一次性发送的最大字节数。request.contentType=... 将数据格式设置为二进制。

然后:

function completeHandler(event:Event):void
{
    //expect a result from server to acknowledge receipt of data
    if (loader.data=="OK")
    {
        if (++currentChunk<totalChunks)
        {
    trace("progress: "+currentChunk+" of "+totalChunks+" sent");
            //send next chunk
            sendChunk();
        }
        else
        {
             trace("finished!");
        }
    }
    else
    {
        trace("OK not receieved from server");
    }
}

这将分段发送整个文件。php 脚本应以“OK”响应(或选择其他适当的响应)——这将显示在 loader.data 中——因此 flash 知道没有出现错误。

我无法在 php 方面为您提供帮助,因为我一直将其留给其他人,但据我所知,它非常简单,因此堆栈上的问题应该可以为您提供答案。

于 2013-02-13T20:36:03.627 回答