【问题标题】:Getting Uploadify to work with asp.net-mvc让 Uploadify 与 asp.net-mvc 一起工作
【发布时间】:2011-04-17 01:03:20
【问题描述】:

我正在尝试让 Uploadify 与我的网站一起使用,但即使在文件发送到服务器之前,我也会收到一个通用的“HTTP 错误”(我这样说是因为 Fiddler 没有向我的控制器显示任何发布请求。

我可以正确浏览要上传的文件。队列中正确填充了要上传的文件,但是当我点击提交按钮时,队列中的元素变为红色并显示 HTTP 错误。

这是我的部分代码:

<% 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>
<% } %>

非常感谢您的帮助!

更新

我在 uploadify 脚本中添加了一个“onError”处理程序,以探索发生了哪个错误,如下例所示

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

发现 info 属性包含 302。我还添加了 "method" 参数以使用 'post' 的值进行上传。

我包含我的控制器操作代码以供参考。我已经阅读了很多关于 uloadify 的帖子,似乎我可以使用具有以下签名的操作...

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

有人可以帮忙吗?

【问题讨论】:

  • 没有机会获得这方面的帮助? :(

标签: asp.net-mvc file-upload uploadify


【解决方案1】:

干得好,问题消失了!

我的代码没有“正确”的问题。插件的使用通常是正确的,但身份验证机制存在问题。

正如每个人都可以在互联网上找到的那样,flash 插件不与服务器端代码共享身份验证 cookie,这就是在我的代码中使用包含身份验证 Cookie 的“scriptData”部分的原因。

问题与控制器使用 [Authorize] 属性修饰的事实有关,这不会让请求到达其目的地。

在uploadify论坛上的另一个用户的帮助下找到的解决方案是编写一个自定义版本的AuthorizeAttribute,如下面的代码所示。

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

使用它来装饰执行上传的控制器/动作,使一切顺利进行。

唯一未解决但不影响代码执行的奇怪问题是,奇怪的是,Fiddler 没有显示 HTTP 帖子。我不明白为什么....

我发布此内容是为了向社区提供。

谢谢!

【讨论】:

  • 那么这是否意味着未经授权的用户可以上传文件?
  • 帖子没有出现在 Fiddler 是因为你需要使用 ipv4.fiddler 作为域而不是 localhost。
  • 感谢这篇文章。有同样的问题,这似乎解决了它。 Uploadify 变得如此错误,以至于我可能只是切换回良好的旧文件输入......
  • @Lorenzo:所以视图或控制器中没有任何变化(除了 [TokenizedAuthorized] 属性来装饰动作?
猜你喜欢
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-11
  • 2016-01-11
  • 2010-09-11
  • 1970-01-01
相关资源
最近更新 更多