Pause and resume download in flex?

2020-06-23 14:03发布

问题:

Is it possible in an air application to start a download, pause it and after that resume it?

I want to download very big files (1-3Gb) and I need to be sure if the connection is interrupted, then the next time the user tries to download the file it's start from the last position.

Any ideas and source code samples would be appreciated.

回答1:

Yes, you would want to use the URLStream class (URLLoader doesn't support partial downloads) and the HTTP Range header. Note that there are some onerous security restrictions on the Range header, but it should be fine in an AIR application. Here's some untested code that should give you the general idea.

private var _us:URLStream;
private var _buf:ByteArray;
private var _offs:uint;
private var _paused:Boolean;
private var _intervalId:uint;
...
private function init():void {
    _buf = new ByteArray();
    _offs = 0;

    var ur:URLRequest = new URLRequest( ... uri ... );
    _us = new URLStream();

    _paused = false;
    _intervalId = setInterval(500, partialLoad);
}
...
private function partialLoad():void {
    var len:uint = _us.bytesAvailable;
    _us.readBytes(_buf, _offs, len);
    _offs += len;

    if (_paused) {
        _us.close();
        clearInterval(_intervalId);
    }
}
...
private function pause():void {
    _paused = true;
}
...
private function resume():void {
    var ur:URLRequest = new URLRequest(... uri ...);
    ur.requestHeaders = [new URLRequestHeader("Range", "bytes=" + _offs + "-")];
    _us.load(ur);
    _paused = false;
    _intervalId = setInterval(500, partialLoad);
}


回答2:

if you are targeting mobile devices, maybe you should take a look at this native extension: http://myappsnippet.com/download-manager-air-native-extension/ it supports simultaneous resumable downloads with multi-section chunks to download files as fast as possible.