Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Uploadify to work with asp.net-mvc

I am trying to get Uploadify to work with my site but I am getting a generic "HTTP Error" even before the file is sent to the server (I say this because Fiddler does not show any post request to my controller.

I can browse correctly for the file to upload. The queue is correctly populated with the file to upload but when I hit on the submit button the element in the queue get a red color and say HTTP Error.

Anyway this is my partial code:

<% using ( Html.BeginForm( "Upload", "Document", FormMethod.Post, new { enctype = "multipart/form-data" } ) ) { %>
<link type="text/css" rel="Stylesheet" media="screen" href="/_assets/css/uploadify/uploadify.css" />
<script type="text/javascript" src="/_assets/js/uploadify/swfobject.js"></script>
<script type="text/javascript" src="/_assets/js/uploadify/jquery.uploadify.v2.1.0.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {

        $("[ID$=uploadTabs]").tabs();

        var auth = "<% = Request.Cookies[FormsAuthentication.FormsCookieName]==null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value %>";
        $('#fileInput').uploadify({
            uploader: '/_assets/swf/uploadify.swf',
            script: '/Document/Upload',
            folder: '/_uploads',
            cancelImg: '/_assets/images/cancel.png',
            auto: false,
            multi: false,
            scriptData: { token: auth },
            fileDesc: 'Any document type',
            fileExt: '*.doc;*.docx;*.xls;*.xlsx;*.pdf',
            sizeLimit: 5000000,
            scriptAccess: 'always', //testing locally. comment before deploy
            buttonText: 'Browse...'
        });

        $("#btnSave").button().click(function(event) {
            event.preventDefault();
            $('#fileInput').uploadifyUpload();
        });

    });
</script>
    <div id="uploadTabs">
        <ul>
            <li><a href="#u-tabs-1">Upload file</a></li>
        </ul>
        <div id="u-tabs-1">
            <div>
            <input id="fileInput" name="fileInput" type="file" />
            </div>
            <div style="text-align:right;padding:20px 0px 0px 0px;">
                <input type="submit" id="btnSave" value="Upload file" />
            </div>
        </div>
    </div>
<% } %>

Thanks very much for helping!

UPDATE:

I have added a "onError" handler to the uploadify script to explore which error was happening as in the following sample

onError: function(event, queueID, fileObj, errorObj) {
    alert("Error!!! Type: [" + errorObj.type + "] Info [" + errorObj.info + "]");
}

and discovered that the info property contains 302. I have also added the "method" parameter to uploadify with the value of 'post'.

I am including my controller action code for information. I have read many posts regarding uloadify and it seems that I can use an action with the following signature...

[HttpPost]
public ActionResult Upload(string token, HttpPostedFileBase fileData) {
    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(token);
    if (ticket!=null) {
        var identity = new FormsIdentity(ticket);
        if(identity.IsAuthenticated) {
            try {
                //Save file and other code removed
                return Content( "File uploaded successfully!" );
            }
            catch ( Exception ex ) {
                return Content( "Error uploading file: " + ex.Message );
            }
        }
    }
    throw new InvalidOperationException("The user is not authenticated.");
}

Can anybody provide some help please?

like image 848
Lorenzo Avatar asked Sep 24 '10 23:09

Lorenzo


1 Answers

Well done and problem gone!

There was not "properly" an issue with my code. The usage of the plugin was generally correct but there was an issue with the authentication mechanism.

As everybody can find on the internet the flash plugin does not share the authentication cookie with the server-side code and this was the reason behind the usage of the "scriptData" section inside my code that contained the Authentication Cookie.

The problem was related to the fact that the controller was decorated with the [Authorize] attribute and this was never letting the request reach its destination.

The solution, found with the help of another user on the uploadify forum, is to write a customized version of the AuthorizeAttribute like you can see in the following code.

/// <summary>
/// A custom version of the <see cref="AuthorizeAttribute"/> that supports working
/// around a cookie/session bug in Flash.  
/// </summary>
/// <remarks>
/// Details of the bug and workaround can be found on this blog:
/// http://geekswithblogs.net/apopovsky/archive/2009/05/06/working-around-flash-cookie-bug-in-asp.net-mvc.aspx
/// </remarks>
[AttributeUsage( AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true )]
public class TokenizedAuthorizeAttribute : AuthorizeAttribute
{
    /// <summary>
    /// The key to the authentication token that should be submitted somewhere in the request.
    /// </summary>
    private const string TOKEN_KEY = "AuthenticationToken";

    /// <summary>
    /// This changes the behavior of AuthorizeCore so that it will only authorize
    /// users if a valid token is submitted with the request.
    /// </summary>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    protected override bool AuthorizeCore( System.Web.HttpContextBase httpContext ) {
        string token = httpContext.Request.Params[TOKEN_KEY];

        if ( token != null ) {
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt( token );

            if ( ticket != null ) {
                FormsIdentity identity = new FormsIdentity( ticket );
                string[] roles = System.Web.Security.Roles.GetRolesForUser( identity.Name );
                GenericPrincipal principal = new GenericPrincipal( identity, roles );
                httpContext.User = principal;
            }
        }

        return base.AuthorizeCore( httpContext );
    }
}

Using this to decorate teh controller/action that does the upload made everything to work smoothly.

The only strange thing that remain unsolved, but does not affect the execution of the code, is that, strangely, Fiddler does not show the HTTP post. I do not understand why....

I am posting this to make it available to the community.

thanks!

like image 182
Lorenzo Avatar answered Nov 12 '22 17:11

Lorenzo