问题在MVC AJAX上传脚本 [英] Issue with AJAX Upload Script in mvc

查看:101
本文介绍了问题在MVC AJAX上传脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这个AJAX文件上传这里脚本 http://www.phpletter.com/Demo / AjaxFileUpload-演示/

I found this ajax file upload script here http://www.phpletter.com/Demo/AjaxFileUpload-Demo/

这是应该将Ajax功能添加到我的文件上传表单

Which is supposed to add ajax functionality to my file upload form

<div id="dialog" title="Upload Image">
           <%
            Html.BeginForm("Upload", "BugTracker", FormMethod.Post,new { id="uploadForm",  enctype = "multipart/form-data"});
           %>

                Select a file: <input type="file" name="file" id="file" />   
                <h6>Upload a screenshot related to the ticket</h6>
                <input type="submit" class="button" value="Upload" id="upload" onclick="uploadImage();" name="submit" />


            <%Html.EndForm();%>
</div>

和我已经建立了一个功能,当我上传表单提交,像这样被称为:

And I have set up a function to be called when my upload form is submitted like so:

function uploadImage() {

    var action = $("#uploadForm").attr('action');

    $.ajaxFileUpload({
        url: action,
        secureuri: false,
        fileElementId: 'file',
        dataType: 'json',
        success: function (data, status) {
            $("#RelatedFileName").val() = data.FileName;
            $("#dialog").dialog("close");
        }
    });
    return false;
}    

但它是正确的跳绳在成功的回调函数,并在浏览器问我是否想下载JSON文件。这里有一个偷看我的上传操作:

but it is skipping right over the success callback function, and the browser asks if I would like to download the json file. Here's a peek at my upload action:

 [HttpPost]
        public ActionResult Upload(HttpPostedFileBase file)
        {
            Regex imageFilenameRegex = new Regex(@"(.*?)\.(jpg|jpeg|png|gif)$");
            if (file != null)
            {
                if (!imageFilenameRegex.IsMatch(file.FileName))
                {
                    return JavaScript("alert('invalid file. you must upload a jpg, jpeg, png, or gif');");
                }
                else
                {
                    string filePath = Path.Combine(HttpContext.Server.MapPath("~/Uploads"), Path.GetFileName(file.FileName));
                    file.SaveAs(filePath);

                    return Json(new { FileName = "/Uploads/" + file.FileName });
                }
            }
            else
            {
                return JavaScript("alert('seriously? select a file to upload before hitting the upload button.');");
            }
        }

我用jQuery.post,它会击中控制器动作,但文件为空,但至少错误会弹出他们的警告框,所以这就是为什么我找到了另一种选择。现在它击中控制器操作和文件被上传,但它不处理任何响应。任何帮助是AP preciated。

I've used jQuery.post and it will hit the controller action but file will be null, but at least errors would pop up in their alert boxes, so that is why I sought out another option. Now it hits the controller action and the file gets uploaded, but it isn't handling any response. Any help is appreciated.

推荐答案

您使用的是希望的text / html 作为响应内容类型,即使你是通过JSON插件。所以,如果你真的想使用它,你需要做的:

The plugin you are using expects text/html as response Content Type even if you are passing JSON. So if you really want to use it you need to do this:

return Content("{ FileName: '/Uploads/' }", "text/html");

当你明白那是废话。

As you understand that's crap.

所以,那就下载的jQuery插件的形式。它更容易使用。你不必在你的HTML做任何事情,这是完全不显眼。刚刚离开的形式是在JavaScript的简单:

So go ahead and download the jquery form plugin. It's much easier to use. You don't have to do anything in your HTML, it's totally unobtrusive. Just leave the form as is and in javascript simply:

$(function() {
    // Only indicate the form id, it will take care of reading the form action, 
    // returning false, ..., all you need is to concentrate 
    // on the success callback
    $('#uploadForm').ajaxForm(function(result) {
        alert(result);
    });
});

还要注意的是在错误的情况下,你不应该返回的JavaScript。你总是需要从控制器动作返回JSON。因此,在发生错误时:

Also notice that in case of error you shouldn't return Javascript. You always need to return Json from your controller action. So in case of error:

return Json(new { errorMessage = "Kaboom", fileName = "" });

在成功的情况下:

and in case of success:

return Json(new { errorMessage = "", fileName = "/Uploads/" + file.FileName });

所以现在你可以检查是否存在通过检查返回的JSON对象的的errorMessage 属性是一个错误:

$('#uploadForm').ajaxForm(function(result) {
    if (result.errorMessage != '') {
        alert(result.errorMessage);
    } else {
        $('#RelatedFileName').val(result.fileName);
        $('#dialog').dialog('close');
    }
});

这篇关于问题在MVC AJAX上传脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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