8 Stimmen

Uploadify mit asp.net-mvc zum Laufen bringen

Ich versuche, Uploadify mit meiner Website zu arbeiten, aber ich bekomme einen allgemeinen "HTTP-Fehler", noch bevor die Datei an den Server gesendet wird (ich sage dies, weil Fiddler keine Post-Anfrage an meinen Controller zeigt.

Ich kann korrekt nach der hochzuladenden Datei suchen. Die Warteschlange wird korrekt mit der hochzuladenden Datei gefüllt, aber wenn ich auf die Schaltfläche "Senden" klicke, wird das Element in der Warteschlange rot und zeigt einen HTTP-Fehler an.

Wie auch immer, dies ist mein Teilcode:

<% using ( Html.BeginForm( "Upload", "Document", FormMethod.Post, new { enctype = "multipart/form-data" } ) ) { %>
<link type="text/css" rel="Stylesheet" media="screen" href="stackoverflow.com/_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>
<% } %>

Vielen Dank für Ihre Hilfe!

UPDATE :

Ich habe dem uploadify-Skript einen "onError"-Handler hinzugefügt, um zu untersuchen, welcher Fehler wie im folgenden Beispiel auftrat

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

und entdeckte, dass die Eigenschaft info Folgendes enthält 302 . Ich habe auch die "Methode" zu uploadify mit dem Wert von 'Post' .

Ich füge meinen Controller-Aktionscode zur Information bei. Ich habe viele Beiträge über uloadify gelesen und es scheint, dass ich eine Aktion mit der folgenden Signatur verwenden können...

[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.");
}

Kann mir bitte jemand helfen?

7voto

Lorenzo Punkte 28601

Gut gemacht und Problem gelöst!

Es war nicht "richtig" ein Problem mit meinem Code. Die Verwendung des Plugins war im Allgemeinen korrekt, aber es gab ein Problem mit dem Authentifizierungsmechanismus.

Wie jeder im Internet nachlesen kann, gibt das Flash-Plugin das Authentifizierungs-Cookie nicht an den serverseitigen Code weiter. Dies war der Grund für die Verwendung des Abschnitts "scriptData" in meinem Code, der das Authentifizierungs-Cookie enthielt.

Das Problem hing mit der Tatsache zusammen, dass der Controller mit dem [Authorize]-Attribut dekoriert war und dies die Anfrage nie ihr Ziel erreichen ließ.

Die Lösung, die ich mit Hilfe eines anderen Benutzers im uploadify-Forum gefunden habe, besteht darin, eine angepasste Version des AuthorizeAttributes zu schreiben, wie sie im folgenden Code zu sehen ist.

/// <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 );
    }
}

Mit diesem zu dekorieren teh Controller/Aktion, die den Upload macht alles reibungslos zu arbeiten.

Die einzige seltsame Sache, die ungelöst bleibt, aber keinen Einfluss auf die Ausführung des Codes hat, ist, dass Fiddler seltsamerweise den HTTP-Post nicht anzeigt. Ich verstehe nicht, warum....

Ich poste dies, um es der Gemeinschaft zugänglich zu machen.

Danke!

CodeJaeger.com

CodeJaeger ist eine Gemeinschaft für Programmierer, die täglich Hilfe erhalten..
Wir haben viele Inhalte, und Sie können auch Ihre eigenen Fragen stellen oder die Fragen anderer Leute lösen.

Powered by:

X