【问题标题】:Issue with AJAX Upload Script in mvcmvc 中的 AJAX 上传脚本问题
【发布时间】:2014-07-11 16:50:22
【问题描述】:

我在这里找到了这个 ajax 文件上传脚本http://www.phpletter.com/Demo/AjaxFileUpload-Demo/

应该为我的文件上传表单添加 ajax 功能

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

我已经设置了一个函数,当我的上传表单被提交时调用:

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 文件。下面是我的上传操作:

 [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,它会触发控制器操作,但文件将为空,但至少在它们的警报框中会弹出错误,所以这就是我寻找另一个选项的原因。现在它触发了控制器操作并且文件被上传,但它没有处理任何响应。任何帮助表示赞赏。

【问题讨论】:

    标签: javascript jquery ajax asp.net-mvc-2


    【解决方案1】:

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

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

    如你所知,那是废话。

    所以继续下载jquery form plugin。它更容易使用。您不必在 HTML 中做任何事情,它完全不显眼。只需将表单保持原样并使用 javascript:

    $(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。所以万一出错:

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

    如果成功:

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

    【讨论】:

      【解决方案2】:

      如果您想进行 ajax 上传,您将需要在 iframe 中进行上传表单。

      见:http://www.ajaxf1.com/tutorial/ajax-file-upload-tutorial.html

      【讨论】:

      • 我在项目的其他地方使用了基于 ajax 的多文件上传,没有你的 iFrame 也能很好地工作。我更愿意让这个成功回调工作,因为上传部分本身工作正常。
      • 没有 iFrame 的唯一方法是使用 flash AFAIK stackoverflow.com/questions/543926/…
      • 我刚刚浏览了脚本 - 这个脚本使用 iframe 重建我的表单,然后进行上传。那么......关于回调的任何想法?
      • 我认为插件期望返回值是文本,您是否尝试过简单地将结果返回为 XML 或文本(不是 json)
      【解决方案3】:

      这里也可以设置内容类型:

      return Json(new { FileName = "/Uploads/filename.ext" }, "text/html", JsonRequestBehavior.AllowGet);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-20
        • 1970-01-01
        • 2011-03-22
        • 1970-01-01
        • 2010-11-18
        • 2011-10-11
        相关资源
        最近更新 更多