Using a File Reference to Upload to ASP.net

If you're looking for a quick way to upload files from Flex to an IIS server using ASP.net, then  you might want to check this out (you'll even get the .net code!)

A  few quick notes before diving into the code; one of the problems with the FileReference object in ActionScript is that it doesn't seem to know how to read any response data from the webserver after the file has been successfully uploaded.  In many cases you'd want to upload the file and then return the name, or id that the server used save it.  This code sample will demonstrate a way around this, but if you absolutely must return data from the server then you'll want to look into using more complicated approaches with the URLLoader object.

Finally, this code sends a query string variable called 'name' that will hold a timestamp of when the file upload occurs.  We'll use this timestamp to rename the file when it's saved on the server.  So this is the hack that allows us to avoid having to read data returned from the server.  We'll determine the final file name in Flex and then send it up to the server along with the file.  The server will then rename the file as specified when it does the save.  This is a crude way to give some insurance that you won't get files with duplicate names that overwrite one another.  Once the upload completes, we use the same time stamp to insert a record into the database, so that we know how to retreive the file at a later time (db code not included).

 

private var fr:FileReference;

private var fileName:String;

 

private function browseForFile(evt:Event):void{
    fr = new FileReference();
    fr.addEventListener(Event.COMPLETE, frComplete);
    fr.addEventListener(Event.SELECT, frSelect);
    fr.addEventListener(IOErrorEvent.IO_ERROR, frIOError);
    fr.addEventListener(SecurityErrorEvent.SECURITY_ERROR, frSecError);
    var fileFilter:FileFilter = new FileFilter("Files", "*.pdf;*.doc;*.docx");
    fr.browse([fileFilter]);
}
private function frSelect(evt:Event):void{
    var urlRequest:URLRequest = new URLRequest();
    //use a timestamp for the file name and then append it to the url

    //as a query string...

    fileName = new Date().getTime().toString();
    urlRequest.url = "YOUR PATH HERE/uploader.aspx?name=" + fileName;

    fr.upload(urlRequest);
}
private function frIOError(evt:IOErrorEvent):void{
    Alert.show(evt.toString());

}
private function frSecError(evt:SecurityErrorEvent):void{
    Alert.show(evt.toString());   

}

private function frComplete(evt:Event):void{
    Alert.show("Upload Complete!);

    //now you can use the fileName var to insert into the db
}


For the .net code I create a new web form that uses a code-behind page. In the declarative code (or the front page) I deleted everything except for the very first line (I left only the page declaration).

Here's the code-behind page:

 

Imports System.IO

Partial Class services_uploader
Inherits System.Web.UI.Page

Dim fileName As String
Dim path As String

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    'the url used to upload the FileReference should have a query string

    'item called 'name' attached to it, we'll use the value to rename our

    'file...
    Dim renameFileTo As String = ""

    If Not Request.QueryString("name") Is Nothing Then
        renameFileTo = Request.QueryString("name")
    End If

    Try
        'set the path to where the file will be saved...
        path = Server.MapPath(".") & "\uploads\"
        For x As Integer = 0 To Request.Files.Count - 1
            fileName = Request.Files(x).FileName
            'get the file extension...
            Dim fnArray() As String = Split(fileName, ".")
            Dim fileExt As String
            If UBound(fnArray) = 1 Then
                'the file extension should be in fnArray(1)...
                fileExt = fnArray(1)
                'verify that the file extension is acceptable...
                If checkFileExtention(fileExt) Then
                    'if renameFileTo is set then we want to save the file as

                    'whatever value it contains
                    If Not String.IsNullOrEmpty(renameFileTo) Then
                        fileName = renameFileTo + "." + fileExt
                    End If
                    'save the file...
                    Request.Files.Item(x).SaveAs(path & fileName)

                Else
                    'invalid file, so let flex know that the upload did not

                    'complete...
                    Response.StatusCode = 500

                End If
            Else
                'invalid file, so let flex know that the upload did not complete...
                 Response.StatusCode = 500
            End If
        Next
        'we need to send something in the response so that flex can trigger

        'the complete event...

        Response.Write("all done")
    Catch ex As Exception
        Response.StatusCode = 500
    End Try

End Sub

'here's a crude way to check the file extension, you might want to check 'the mime type instead...

Function checkFileExtention(ByVal ext As String) As Boolean
    Dim allowFile As Boolean
        Select Case ext
            Case "pdf"
                allowFile = True
            Case "doc"
                allowFile = True
            Case "docx"
                allowFile = True
            Case Else
                allowFile = False
        End Select
        Return allowFile
End Function

 

End Class

 

 

 

1 Comment - Average Rating:5

Comments:
Partial C# conversion:

protected void Page_Load(object sender, EventArgs e)
{
//Trace.IsEnabled = true;
// Trace.TraceFinished = TraceMode.SortByTime;

string path = "";
string filenname = "";

try
{
//set the path to where the file will be saved...
path = Server.MapPath(".") + "\\uploads\\";

for (int x = 0; x < Request.Files.Count; x++)
{
filenname = Request.Files[x].FileName;

//get the file extension...
string[] fnArray = filenname.Split('.');
string fileExt = "";
//the file extension should be in fnArray(1)...
fileExt = fnArray[1];
//verify that the file extension is acceptable...

//save the file...
Request.Files[x].SaveAs(path + filenname);
//invalid file, so let flex know that the upload did not complete...

//Response.StatusCode = 500;
}

//we need to send something in the response so that flex can trigger

//the complete event...
}
catch(Exception ex)
{
}

}
Rating: 5
Date Posted: January 13th, 2011



RECENT ARTICLES