Download a file with Adobe AIR

2020-01-30 09:23发布

How do I download a file from the internet in a Flex based AIR application.

I tried using a file with url set to the address, but I got a file does not exist error when I tried to save it. And it is really hard to google for help on this issue.

5条回答
何必那么认真
2楼-- · 2020-01-30 09:24

I used seanalltogether's answer, and wrote this class to handle file downloading.

It is pretty simple. create a var downloader = new FileDownloader("url", "Local/Path"); and call downloader.load() to start downloading.

It also supports setting a function to be called when done, and at points while downloading. Passing the onProgress function the number of bytes that have been downloaded. ( I could not figure out how to get a fraction, since I could not figure out how to query the size of the file before it was downloaded)

package com.alex{
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.net.URLRequest;
import flash.net.URLStream;
import flash.utils.ByteArray;

public class FileDownloader
{

    // Class to download files from the internet

    // Function called every time data arrives
    //      called with an argument of how much has been downloaded
    public var onProgress :Function = function(t:uint):void{};
    public var onComplete :Function = function():void{};
    public var remotePath :String = "";
    public var localFile :File = null; 

    private var stream :URLStream;
    private var fileAccess :FileStream;

    public function FileDownloader( remotePath :String = "" , localFile :File = null ) {

        this.remotePath = remotePath;
        this.localFile = localFile;
    }

    public function load() :void {
        if( !stream || !stream.connected ) {
            stream = new URLStream();
            fileAccess = new FileStream();

            var requester :URLRequest = new URLRequest( remotePath );
            var currentPosition :uint = 0;
            var downloadCompleteFlag :Boolean = false;

            // Function to call oncomplete, once the download finishes and
            //      all data has been written to disc               
            fileAccess.addEventListener( "outputProgress", function ( result ) :void {
                if( result.bytesPending == 0 && downloadCompleteFlag ) {

                    stream.close();
                    fileAccess.close();
                    onComplete();
                }
            });

            fileAccess.openAsync( localFile, FileMode.WRITE );

            stream.addEventListener( "progress" , function () :void {

                var bytes :ByteArray = new ByteArray();
                var thisStart :uint = currentPosition;
                currentPosition += stream.bytesAvailable;
                // ^^  Makes sure that asyncronicity does not break anything

                stream.readBytes( bytes, thisStart );
                fileAccess.writeBytes( bytes, thisStart );

                onProgress( currentPosition );                      
            });

            stream.addEventListener( "complete", function () :void {
                downloadCompleteFlag = true;
            });

            stream.load( requester );

        } else {
            // Do something unspeakable
        }
    }
}}
查看更多
姐就是有狂的资本
3楼-- · 2020-01-30 09:26

You want to choose from 2 api combos to accomplish this.

Version 1 is URLLoader and FileStream

Using this combination of class, you would load the file from your server in to air via the URLLoader object. This will download the file in to memory and then notify you when the download is complete. Make sure you initiate the download with a dataFormat of URLLoaderDataFormat.BINARY. You would then initiate a Filestream object and write it out to the disk using writeBytes().

Version 2 is URLStream and FileStream

URLStream is very similar to URLLoader, but instead of waiting for the file to completely download before using the result, data is made available to you during the download. This method works well for large files because you don't have to wait for the full download to start saving it to disk, and you also save on memory since once the player hands it off to you it can release the memory related to that data. YOu would use filestream in exactly the same way, you would just end up doing a writeBytes() on each chunk of the file as it streams in.

查看更多
Anthone
4楼-- · 2020-01-30 09:30

Please also check the URLLoader class for downloading files. An excellent example is here: http://www.adobe.com/devnet/air/flex/articles/exploring_file_capabilities.html

This worked out to be very fast for me, as compared to the URLStream class, which was taking ages, and a lot of CPU to download files.

查看更多
再贱就再见
5楼-- · 2020-01-30 09:45

To build on seanalltogether's second idea, here is a function that should download a file from the internet, and save it to disk (in the specified file name on the desktop):

downloadFile: function (url, fileName) {
    var urlStream = new air.URLStream();
    var request = new air.URLRequest(url);
    var fileStream = new air.FileStream();
    // write 50k from the urlstream to the filestream, unless
    // the writeAll flag is true, when you write everything in the buffer
    function writeFile(writeAll) {
        if (urlStream.bytesAvailable > 51200 || writeAll) {
            alert("got some");
            var dataBuffer = new air.ByteArray();
            urlStream.readBytes(dataBuffer, 0, urlStream.bytesAvailable);
            fileStream.writeBytes(dataBuffer, 0, dataBuffer.length);
        }
        // do clean up:
        if (writeAll) {
            alert("done");
            fileStream.close();
            urlStream.close();
            // set up the next download
            setTimeout(this.downloadNextFile.bind(this), 0);
        }
    }

    urlStream.addEventListener(air.Event.COMPLETE, writeFile.bind(this, true));
    urlStream.addEventListener(air.ProgressEvent.PROGRESS, writeFile.bind(this, false));

    var file = air.File.desktopDirectory.resolvePath(fileName);
    fileStream.openAsync(file, air.FileMode.WRITE);

    urlStream.load(request);

}

Note: This solution uses Prototype, and AIRAliases.js.

查看更多
smile是对你的礼貌
6楼-- · 2020-01-30 09:47

Check out the flash.net.URLRequest class which will help you to download the file.

查看更多
登录 后发表回答