Upload Multiple Files Using ASP.NET & Adobe Flex

 In this blog post, Haissam Abdul Malak will demonstrate how to upload multiple files in ASP.NET taking advantage of Adobe Flex technology.

Why The integration between Flex and ASP.NET

    Using the File Upload control provided in ASP.NET, the user can't select more than 1 file at a time however in Adobe Flex the user can select multiple files in the open dialog box through the
FileReferenceList.browse() method also one important feature to mention is the ability to monitor the upload progress. In other words, you can handle the Progress event to display the number of bytes being uploaded and the total size of each uploaded file.

After the user selects the files, you can access them by the fileReferenceList.fileList property which will return an Array of the selected files. In this way, You can loop through the array's elements and start the upload process for each file. To successfully upload a file, you need to send a "Post" request to a URL (the handler will be an aspx page) which will save the files in the application root folder.


Creating the Flex Application

If you have a Adobe Flex builder, you can open it and click on File --> New --> Flex Project.

An .mxml file will be created, Just copy and paste the below code

MXML:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="myFunction();">
<mx:Button x="10" y="10" label="Choose Files" id="btnSelectFiles"/>
<mx:Button x="114" y="10" label="Upload" id="btnUpload" visible="false"/>
<mx:Label x="10" y="208" width="100%" id="lblFileName" fontWeight="bold"/>
<mx:List borderStyle="none" backgroundAlpha="0" x="10" y="40" width="30%" id="listSelectedFiles" visible="false" />
<mx:Label x="10" y="234" width="100%" id="lblUploadedBytes" fontWeight="bold"/>
<mx:Label x="10" y="260"  width="100%" id="lblTotalBytes" fontWeight="bold"/>
<mx:Script>
    <![CDATA[
        import mx.messaging.AbstractConsumer;
        public var fileReferenceList:FileReferenceList = new FileReferenceList();
        public function eventResponse(Event:MouseEvent):void
        {
            // Set the file filters in the open dialog box
            var typeFiler:FileFilter = new FileFilter("All","*.*");
            // show the dialog box
            fileReferenceList.browse([typeFiler]);
        }
        public function selectResponse(event:Event):void
        {
            // Create an array with the size of the selected files.
            var filesSelected:Array = new Array(fileReferenceList.fileList.length);
            // Loop through all the selected files and add their names to the List control
            for(var i:int=0;i<fileReferenceList.fileList.length;i++)
            {
                var fileReference:FileReference = fileReferenceList.fileList[ i ];
                filesSelected[ i ] = fileReference.name;
            }
            listSelectedFiles.dataProvider = filesSelected;
            listSelectedFiles.visible = true;
            btnUpload.visible = true;
        }
        public function myFunction(): void
        {
            // This function is called on creationComplete event of this application
            // Add event handler for the mouse click on the selectFiles button
            btnSelectFiles.addEventListener(MouseEvent.CLICK, eventResponse);
            // Add event handler for the mouse click on the upload button
            btnUpload.addEventListener(MouseEvent.CLICK, btnUploadResponse);
            // Add event handler for the select action in the open file dialog box
            fileReferenceList.addEventListener(Event.SELECT,selectResponse);
        }
        public function UploadFiles():void    
        {
            // If the user selected 1 or multiple files
            if(fileReferenceList.fileList.length > 0)
            {
                // For each file selected
                for(var i:int=0;i<fileReferenceList.fileList.length;i++)
                {
                    // Create a FileReference instance of each file
                    var fileReference:FileReference = fileReferenceList.fileList[ i ];
                    // Create a new URLRequest class: The parameter is the aspx handler page
                    var request:URLRequest = new URLRequest("http://localhost/FlexUpload/Default.aspx");
                    // Add event handler for the progress
                    fileReference.addEventListener(ProgressEvent.PROGRESS, progressStatus);
                    // Set the content type
                       request.contentType = "application/octet-stream";
                      // Set the method of the request
                    request.method = "POST";
                    // Upload the file
                    fileReference.upload(request,fileReference.name,false);
                }
            }    
        }
        public function btnUploadResponse(event:Event):void
        {
            // Disable the Select files button, upload button, and call the UploadFiles function
            btnSelectFiles.enabled = false;
            btnUpload.enabled = false;
            UploadFiles();
        }
        public function progressStatus(event:ProgressEvent):void
        {
            var file:FileReference = FileReference(event.target);
            // Set the name of the currently being uploaded file
            lblFileName.text = "Uploading File: " + file.name;
            // Set the number of bytes being uploaded
            lblUploadedBytes.text = "Bytes Uploaded: " + event.bytesLoaded;
            // Set the total number of bytes
            lblTotalBytes.text = "Total Size: " + event.bytesTotal + " bytes";
        }
    ]]>
</mx:Script>

</mx:Application>


ASP.NET Application

I decided to post the above code in case anyone wants to change the UI or some functionality of this control. However, if you want to use it as it is, All you need to do is to embed the ".swf" using the

Object tag file found in the attached zip file of this current post into your application.
Now create a folder "UploadedFiles" which will contain all the uploaded files (do not forget to give IUSR_<machinename> read/write permissions).

After this stage, you need to create a page called "UploadHandler.aspx" which will received the file and save it in the "UploadedFiles". Copy the below into the page_load event

            for (int i = 0; i < Request.Files.Count; i++)
            {
                string fileName = System.IO.Path.GetFileName(Request.Files[ i ].FileName);
                Request.Files[ i ].SaveAs(Server.MapPath("~/UploadedFiles/") + fileName);
            }


After you complete the above steps, you can run the application and see how it functions.

Hope this Helps,

Comments

# re: Upload Multiple Files Using ASP.NET & Adobe Flex

Saturday, March 29, 2008 8:19 PM by JoshC

Thanks fo the post. I did not know you could use this method.

Josh Coswell

http://riverasp.net

# re: Upload Multiple Files Using ASP.NET & Adobe Flex

Monday, March 31, 2008 7:08 PM by jgermain

Great post! Will this work if the website is set up for integrated windows authentication? It's my understanding that the current version of Flash does not properly handle HTTP authentication.

Thanks.

# re: Upload Multiple Files Using ASP.NET & Adobe Flex

Tuesday, April 08, 2008 6:22 PM by bigdubb

One question and a comment...

1.  When attempting to import the mx.messaging.AbstractConsumer this is not a found library.  Is this Flex 3 or Flex 2

As for windows authentication what we have done is created a dummy user with authentication and have that user's credentials passed as part of the webconfig file. HTH.

Great article BTW I am implementing this as part of a title window to operate as part of a larger flex application.  

# re: Upload Multiple Files Using ASP.NET & Adobe Flex

Wednesday, April 09, 2008 2:01 AM by haissam

Actually you don't need this library to let this example work. Maybe it was added because i used a class contained in that library and thn i removed its code. However, this library could be found in flex 3

# re: Upload Multiple Files Using ASP.NET & Adobe Flex

Tuesday, April 15, 2008 12:18 AM by bigdubb

I'd like to test for errors on the upload event, in the advent the file doesn't upload.  

Do you have any suggestions for the testing of the  upload file?

# re: Upload Multiple Files Using ASP.NET & Adobe Flex

Friday, September 12, 2008 1:44 AM by aysha

Hye

amazing article indeed ..... but how can we put check in flex that only images and music files are uploaded

# re: Upload Multiple Files Using ASP.NET & Adobe Flex

Friday, September 12, 2008 2:43 AM by haissam
The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.