获取Uploadify用asp.net-MVC工作 [英] Getting Uploadify to work with asp.net-mvc

查看:73
本文介绍了获取Uploadify用asp.net-MVC工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让Uploadify与我的网站工作,但我得到一个通用的HTTP错误甚至在文件被发送到服务器(我这样说是因为提琴手不显示任何POST请求我的控制器。

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.

我可以正确浏览要上传的文件。队列正确的填充文件上传,但是当我打提交按钮在队列中的元素得到了红色,说HTTP错误。

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.

反正这是我的部分code:

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!

更新

我添加了一个onError的处理程序的脚本uploadify探索其中的错误发生了如下示例中

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 + "]");
}

和发现信息属性包含的 302 。我还添加了方法与参数的值uploadify

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

我包括我的控制器操作code的信息。我已经阅读了有关uloadify很多帖子,似乎我可以使用具有以下签名的动作...

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?

推荐答案

做得很好,问题消失了!

Well done and problem gone!

有没有正常与我的code的一个问题。该插件的使用是通常是正确的,但有一个与身份验证机制的问题。

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.

由于每个人都可以在互联网上找到的flash插件不共享服务器端code中的身份验证cookie,这是scriptData部分包含我的code里面的使用背后的原因身份验证cookie。

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.

解决方案,搭配上uploadify论坛的其他用户的帮助下发现的,是写AuthorizeAttribute定制版一样可以在以下code看到的。

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.

这仍然没有得到解决,但不影响code的执行的唯一奇怪的是,奇怪的是,提琴手不显示HTTP职位。我不明白为什么....

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.

谢谢!

这篇关于获取Uploadify用asp.net-MVC工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆