【问题标题】:Loading images dynamically using JQuery使用 JQuery 动态加载图像
【发布时间】:2012-09-07 16:36:06
【问题描述】:

我有一个场景,我让用户在我的网页上选择要上传到他/她的用户个人资料的图像。我正在为我的网站使用 .net 的 MVC3 架构。我需要的是在他选择他想要的图像之后但在我将其存储在数据库中之前,图像显示在页面上。我四处搜寻,最后尝试了这个,我的一个朋友说对他有用:

在我尝试过的视图中:

<div class="floatRight">
    <a onclick="opendialogbox('imageLoad2');" style="cursor: pointer">Photo</a>
    <img src="… " width="16" height="16" id="imgThumbnail2" alt="photo" />
    <input type="file" name="imageLoad2" accept="image/*" id="imageLoad2" onchange="ChangeImage('imageLoad2','#imgThumbnail2')" hidden="hidden" />
</div>

<script type="text/javascript">
    function opendialogbox(inputid) {
        document.getElementById(inputid).click();
    }

function ChangeImage(fileId, imageId) {
        var ext = document.getElementById(fileId).value.match(/\.(.+)$/)[1];
        switch (ext.toLowerCase()) {
            case 'jpg':
            case 'bmp':
            case 'png':
            case 'gif':
            case 'jpeg':
                {
                    var myform = document.createElement("form");
                    myform.style.display = "none";
                    myform.action = "/ImagePreview/AjaxSubmit";
                    myform.enctype = "multipart/form-data";
                    myform.method = "post";
                    var imageLoad;
                    var imageLoadParent;
                    //test browser used then submit form
                    $(myform).ajaxSubmit({ success:
                        function (responseText) {
                            var d = new Date();
                            $(imageId)[0].src = "/ImagePreview/ImageLoad?a=" + d.getMilliseconds();
                            if (document.all || is_chrome)//IE
                                imageLoadParent.appendChild(myform.firstChild);
                            else//FF                     
                                document.body.removeChild(myform);
                        }
                    });
                }
                break;
            default:
                alert('Error, please select an image.');
        }

    }

</script>

在我尝试过的控制器中:

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AjaxSubmit(int? id)
        {
            Session["ContentLength"] = Request.Files[0].ContentLength;
            Session["ContentType"] = Request.Files[0].ContentType;
            byte[] b = new byte[Request.Files[0].ContentLength];
            Request.Files[0].InputStream.Read(b, 0, Request.Files[0].ContentLength);
            Session["ContentStream"] = b;
            HttpPostedFileBase file = Request.Files[0];
            string myFilePath = Server.MapPath(Url.Content("~/Content/themes/base/images/Auxiliar.png"));
            file.SaveAs(myFilePath);
            return Content(Request.Files[0].ContentType + ";" + Request.Files[0].ContentLength);
        }



        public ActionResult ImageLoad(int? id)
        {
            byte[] b = (byte[])Session["ContentStream"];
            int length = (int)Session["ContentLength"];
            string type = (string)Session["ContentType"];
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = type;
            Response.BinaryWrite(b);
            Response.Flush();
            Response.End();
            Session["ContentLength"] = null;
            Session["ContentType"] = null;
            Session["ContentStream"] = null;
            return Content("");
        }

现在我认为这一切都是有道理的,但是当我在我的网站上尝试时,该方法永远不会到达服务器(我在控制器中两种方法的开头都放置了一个断点)。我还使用了firefox的firebug来跟踪页面上的脚本,直到它到达该行:

$(myform).ajaxSubmit({ success:
                        function (responseText) {
                            var d = new Date();
                            $(imageId)[0].src = "/ImagePreview/ImageLoad?a=" + d.getMilliseconds();
                            if (document.all || is_chrome)//IE
                                imageLoadParent.appendChild(myform.firstChild);
                            else//FF                     
                                document.body.removeChild(myform);
                        }
                    });

在这里它会继续,但永远不会进入成功条件。我认为页面上包含的 JQuery 版本可能有问题,并注意到我的朋友网站包括:jquery-1.5.1.min.js、jquery-1.3.2.js 和 jquery_form.js

我将这些添加到我的网站(使用 jquery-1.7.2.min.js),但问题仍然存在。不确定包含各种版本的 jquery 是否会导致与方法发生某种冲突,或者问题是否出在其他地方。

我将非常感谢有关此事的任何帮助。 提前致谢。

【问题讨论】:

    标签: jquery asp.net-mvc-3


    【解决方案1】:

    唐尼,仍然很难推断出问题所在,但您可以采取一些措施来确定问题的确切性质。

    首先,您正在处理成功条件,但您还需要使用与上面写的类似的匿名函数来处理错误条件。 http://api.jquery.com/jQuery.ajax/ 对此有一些信息,但基本上你要写:

    $(myform).ajaxSubmit({ success: function (responseText) {
                                      // your success method
                                    },
                           error: function (responseText) {
                                      // your error method
                                    }
                    });
    

    接下来,FireBug 很棒,但您还需要使用它的网络监控功能,而不仅仅是脚本调试器。很可能有一个非常相关的 500 或 404 返回到那里,而您不知道。

    如果是404,可能和这一行有关:

    myform.action = "/ImagePreview/AjaxSubmit";
    

    我通常新建一个 var 并让 MVC 像这样构建我的操作 url:

    var actionUrl = '@Url.Action("Action", "Controller")'
    

    作为最佳实践,我通常会将此 URL 作为我的视图模型的一部分注入,或者将其存储在视图中的隐藏字段中,但这也可以。

    希望这些提示对您有所帮助。干杯。

    【讨论】:

    • 首先感谢您的宝贵时间。您发送的链接帮助我实现了一件事...... $(myform).ajaxsubmit() 方法不是 jquery 库的一部分......它实际上是 jquery_forms 插件的一部分。我现在正在研究这个。再次感谢
    猜你喜欢
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    相关资源
    最近更新 更多