Browse and download files with Flex, Spring and BlazeDS

After writing about Uploading Files with Flex and Spring via BlazeDS the next logical step is to write another example of how to browse and download them

This example will show how to get a list of all files and folders from a specific directory on the server, display them in the client’s application, browse these directories and/or download specific files.

So you may see that in the previous post I used Flex 4. I really wanted to create this example also with Flex 4, but I had problems with creating an itemRenderer for DataGrid, even found about this MXDataGridItemRenderer but still. I would appreciate if someone would comment about how to get over this. But whatsoever the example that I’m going to show here is created with Flex 3.5 and we all know how cool is it 🙂

This time we will start with the Spring implementation. So first we have this variable

private File currentDirectory = new File(System.getProperty("user.home"));

This will keep track of our current directory, as we will browse the content from the client application. I’ve taken a note from Helen Neely on my previous post and now the path is OS independent and it points to the user’s home directory.

@RemotingInclude
public List listFiles() {
    
    File files[] = currentDirectory.listFiles();
    ArrayList allFiles = new ArrayList();
    
    for(int i = 0; i < files.length; i++){
        if(!files[i].isHidden())
        {
            allFiles.add(new FileInfo(files[i].getName(),
                    files[i].length(), files[i].isDirectory()));
        }
    }
    return allFiles;
}

This method takes all the files and folders that are in the current directory that are not hidden (personal likeness) adds them in an ArrayList and returns the list. You can see that here we are creating new objects of type FileInfo, that is just a small class I wrote that has properties like name, size, isDir and data . There is also a corresponding to this class in the Flex project so we can map them.

@RemotingInclude
public void changeDir(String dir) {
    if(StringUtils.hasText(dir)){
        File tempDirectory = new File(currentDirectory.getPath() + File.separator + dir);
        if(tempDirectory.exists() && tempDirectory.isDirectory())
            currentDirectory = tempDirectory;
    }
}

When called this method with a name of folder we look if there is a folder with this name in our current directory and we change the current directory to it.

@RemotingInclude
public FileInfo downloadFile(String fileName) throws Exception {
    
    File file = new File(currentDirectory.getPath() + File.separator + fileName);
    FileInputStream input = new FileInputStream(file);
    byte data[] = new byte[(int)file.length()];
    input.read(data);
    
    return new FileInfo(file.getName(), file.length(), file.isDirectory(),
            data);
}

Basically this creates a new FileInputStream for the file specified by the current directory and filename and reads it’s data in a array of bytes and then we return a new FileInfo instance that holds these bytes.

Having these methods we are ready to write our client application.
On creation complete we call

remoteBrowseDownload.listFiles();

place a DataGrid and for it’s dataProvider bind to the last result of this operation

<mx:DataGrid id="dataGrid" width="100%" height="100%"
     doubleClickEnabled="true" doubleClick="dataGridDoubleClick(event)"
     dragEnabled="true"
     dataProvider="{remoteBrowseDownload.listFiles.lastResult}">

In the data grid when a user double clicks on a folder we will have to open the folder and display it’s content

public function changeDir(dir:String):void
{
    remoteBrowseDownload.changeDir(dir);
    remoteBrowseDownload.listFiles();
}

Where “dir” is the name of the selected folder.
When the item is not a directory, we have to download it. It is done by this function:

public function downloadFile(file:FileInfo):void
{
    for (var i:int = 0; i < downloadedFiles.length; i++)
    {
        if(file.name == downloadedFiles[i].name && 
            file.size == downloadedFiles[i].size)
            return;
    }
    
    remoteBrowseDownload.downloadFile(file.name);
    
    file.isDownloaded = false;
    downloadedFiles.addItem(file);
}

We are doing a simple check whether this file is already downloaded and if it’s not we call the downloadFile method from our service with only the name of the file and add it in this downloadedFiles array that holds all of our downloaded files. You can see how fast the data is transfered, this is thanks to BlazeDS and AMF.

As this downloading could take longer (depending on the file size), we provide an event handler for the result., that just set the flag isDownloaded to true.

private function onFileDownloaded(event:ResultEvent):void
{
    var file:FileInfo = (FileInfo)(event.result);
    file.isDownloaded = true; 
    for (var i:int = 0; i < downloadedFiles.length; i++)
    {
        if(file.name == downloadedFiles[i].name && 
            file.size == downloadedFiles[i].size)
        {
            downloadedFiles.setItemAt(file, i);
        }
    }                
}

When files are being downloaded we display them in another grid with a progress bar and when the download completes, a button  “save” appears to allow the user to save the file on his file system. To save a file we use the FileReference.save.

public function saveFile(file:FileInfo):void
{
    var fileRef:FileReference = new FileReference();
    fileRef.save(file.data, file.name);
}

Have in mind that use this feature you have to target your application to use Flash player 10.

So basically, that’s it. I’ve also played to add drag and drop support and other stuff, but yo could see by downloading the source.

Download Flex and Spring projects

EDIT: From the Spring project I have made a Maven 2 project, that you can also download

Advertisements

16 comments

  1. Makariev · March 12, 2010

    Looks amazing ! Together with your previous post, it creates a complete picture of handling file uploads/downloads with Flex/Spring/BlazeDS . It would be really great, if you can create your examples with Maven 2 , so that NetBeans users like me could easily reuse them 🙂

    Like

  2. Tony Georgiev · March 15, 2010

    Thanks for your comment!
    I've looked on your suggestion, and now the Eclipse projects can be built with Maven 2, but only the Java ones. You can see the download links on the endings of this and the previous (file upload) posts.
    As with Flex for now you can build it only with Flex/Flash Builder. I think that later I could write a post about building Flex apps with Maven 2

    Like

  3. Anonymous · August 5, 2010

    How do you save with flex 3.5 instead of 4? 3.5 FileReference doesn't have save method.

    Like

  4. Tony Georgiev · August 5, 2010

    It does, but you have to compile your application for flash player 10

    Like

  5. Anonymous · January 28, 2011

    how to browse and display the contents in selected folder

    Like

  6. Tony Georgiev · January 28, 2011

    I dont quite understand you… This whole article explains how to browse and display contents of a selected folder on the server. If you want to see how to browse files on the clients machine see http://tgeorgiev.blogspot.com/2010/02/file-upload-with-flex-and-spring.html

    Like

  7. Anonymous · November 17, 2012

    If a natural ԁisаster ѕtriκes, are you pгepаrеd for it?
    If the аnѕwer is nο, tаke a lοοk at this fгee guide
    on suгvival аt http://survive.top-informatiοn.
    net/
    My web site: The hCG Diet: A healthy stepping stone for weight management – hcg diet injections success

    Like

  8. Anonymous · November 17, 2012

    Α high quality cameга for a νeгy attractive price
    oг juѕt a bad quality рicture? Discover on the full review
    at httр://reνіeωs.top-infοrmation.
    net/canon-рοwеrshot-ѕx50-hs-гeviеw/
    Take a look at my web-site howluciddreamtonight.wordpress.com

    Like

  9. Anonymous · November 17, 2012

    Need hosting? Get the toρ dеals at http:
    //hoѕting.tоp-information.nеt/
    Also visit my weblog Cool Fish Tanks

    Like

  10. Anonymous · November 17, 2012

    A hіgh qualitу camеra for
    a very attгаctіve priсe or just a bad qualіty piсtuге?

    Discover оn the full reviеw at http://гevieωs.
    tοp-informatіon.nеt/cаnon-pоwershot-sх50-hs-reviеw/
    my webpage > Electric Garage Heaters

    Like

  11. Anonymous · November 17, 2012

    А tablet and a laptop сomе togethеr at http:
    //wωw.ѕquidoo.com/samsung-аtiv-smаrt-pc-pro-700t-reνiew
    Here is my site :: anxietysymptomsinmen.net

    Like

  12. Anonymous · November 17, 2012

    A high quality сameгa foг a very attrаctive pricе or juѕt a bad quality pictuгe?
    Dіscover on the full гeviеw at http://revіewѕ.
    top-informatіon.net/canon-рοwershot-sx50-hs-revіew/
    Also see my web site :: claninglaminatefloors.com

    Like

  13. Anonymous · November 18, 2012

    Just submit your email аt httр://ωww.
    frеeіpad3.allthebeѕtproductѕ.net and sign up to test Applе's products! You get to keep them afterwards!
    Here is my page :: small motorhomes

    Like

  14. Anonymous · November 21, 2012

    Gettіng а goοd HD TV has neνer been eaѕier.
    Discovеr the right modеl foг yοu anԁ уouг poсkеt wіth our review at http:
    //гevieωs.tοp-infoгmatіon.
    nеt/samѕung-un40eh6000-review/
    Also see my webpageNail Gun Reviews

    Like

  15. Anonymous · November 21, 2012

    Having trouble losing weight? How about tаκіng a look at what is cοnsіdеrеd to be a fat burner in а bottle?
    Check οur guiԁe οn how to uѕe Rapberrу Ketones аnd gеt them fоr the best prіce at http:
    //rasρberryketones.heaгtdata.nеt/
    My blog post Buy 3D Glasses

    Like

  16. Anonymous · November 22, 2012

    Getting a good HD ΤV has nеνer been easier. Discover the right
    mоdel for you and уour poсket with our reνіew at http://reviews.
    top-information.net/samsung-un40eh6000-review/
    Feel free to surf my web blog :: Allthebestproducts.Net

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s