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,

Attachment: FlexUpload.zip
Published 29 March 2008 09:08 PM by haissam

Comments

# JoshC said on 29 March, 2008 08:19 PM

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

Josh Coswell

http://riverasp.net

# jgermain said on 31 March, 2008 07:08 PM

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.

# bigdubb said on 08 April, 2008 06:22 PM

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.  

# haissam said on 09 April, 2008 02:01 AM

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

# bigdubb said on 15 April, 2008 12:18 AM

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?

# aysha said on 12 September, 2008 01:44 AM

Hye

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

# haissam said on 12 September, 2008 02:43 AM

Please check below link

www.aboutflex.net/.../filefilter-open-a-browse-window-with-a-custom-filter

# blue said on 16 November, 2008 09:38 PM

Hi haissam,

May I know how to remove the bgcolor? I just want plain white without any background set to it.

FYI, I don't have Adobe Flex builder, but I intend to use it in my ASP.NET application to browse multiple files at a time and to upload them at once.

Please help, looking forward to your reply.

Thank you.

# blue said on 16 November, 2008 09:41 PM

Hi, I am totally new to Flex here, and I don't have Adobe Flex Builder as well, but I would like to make use of the .swf file that found in your example in my ASPNET web site, to be able to browse multiple files at a time and upload them at once.

Please advise on how to remove the bgcolor that found in your example? can it be done without Adobe Flex Builder? Please help. I am looking forward to your reply.

Thanks.

# wilmetrix said on 06 March, 2009 08:56 AM

Hi hassam, Thanks for this excellent tool.

Look, I tested and got an error message that says: "Error #2044: Unhandled ioError:. text=Error #2038: File I/O Error". I have already given read/write permissions to IUSR_(my machine name) user on the UpLoadedFiles folder.

# wilmetrix said on 06 March, 2009 09:01 AM

Hi hassam,

I'm new with ASP and Flex and tested your solution but got the following error message: "Error #2044: Unhandled IOErrorEvent:. text=Error #2038: File I/O Error.". I already granted read/write permissions to the IUSR_(mymachine) user to the UpLoadedFiles folder.

Does anyone know how to fix this in IIS and ASP.NET?

# wilmetrix said on 06 March, 2009 10:35 AM

Hi, I'm getting the error message: Error #2044: Unhandled IOErrorEvent:. text=Error #2038: File I/O Error.

Please help me to fix this. I have given permissions to user IUSR_(mymachine) and nothing. I also disabled the firewall just for testing and nothing.

# haissam said on 06 March, 2009 06:24 PM

Try the below

Windows XP/2000 : give ASPNET account read/write permissions on the folder

Windows 2003/Vista: NETWORK SERVICE account read/write permissions.

# wilmetrix said on 10 March, 2009 11:37 AM

Hi, haissam.

Thanks for your answer. If you mean to grant read/write permissions to the IUSR_MyMachineName user, I have already done it. Is it another thing? Would you please give me some directions about how to do that? Thanks.

# wilmetrix said on 10 March, 2009 01:31 PM

Hi haissam.

Finally I made it work, I found out that  ASP.NET wasn't working with the same FrameWork version that the program uses in my machine, so I followed this instructions:

1)Open a command prompt and navigate to this dir C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

2) Run these commands in this order from command prompt:

a. aspnet_regiis.exe –i

b. aspnet_regiis.exe –e

3) Restart IIS.

=======================================

Anyway, thank you very much for all your help and support, I really appreciate it.

# haissam said on 10 March, 2009 03:35 PM

Glad to hear it finally worked with you. Hope it was at the limit of your expectations.

Regards,

# Cady said on 29 August, 2009 04:28 PM

thank you, this code is cool

one question though, if selecting multiple files, the progress won't appear

how to do?

# Garath said on 21 September, 2009 03:25 PM

I use this on a site with integrated Windows authentication. unfortunatly request.files is empty. Any ideas?

# Dedussy said on 25 November, 2009 01:37 AM

Great. Nice to find a post with both Flex and ASP code.

Good job. Thanks

# harkishan said on 16 December, 2009 01:25 AM

thanks alot man...this is what i was searching for weeks....

# webDa said on 16 December, 2009 01:44 PM

I have ASP.NET application with Windows Authentication. The flex upload does not even get to my page and the browser crashes. Using fiddler I saw that I get 401 (unauthorized). Please help.

# Kman said on 17 December, 2009 01:37 PM

How did you solve the problem of Windows Authentication? I have a site with windows integrated security and I need to upload a file using Flex filereference.

Any help will be appriciated.

# Kman said on 17 December, 2009 01:42 PM

I have a site using Integrated Windows Security for authentication. How can I upload a file using Flex filereference without changing the site security settings? I keep getting errors.

# Vijendra said on 18 December, 2009 12:55 AM

Thanks alot man it helps me lot.Searching from last 2 days Finally catch solution from u....

Very mant thanks

viju18445@gmail.com

This site

Search

Go

This Blog

Syndication

Sponsors

  • MaximumASP
  • Breaking News
  • Find a Job
  • Social Bookmarking
    Tidebuy Reviews
    Online Shopping
    asp.net hosting
    UK online local dating