使用 form 和 iframe 实现图片上传回显

摘要:主要利用 form 的 target 属性,在提交表单之后 response 返回到 iframe 中。form 的 action 可以自己写,也可以直接利用 富文本编辑器的接口实现上传

主要利用 form 的 target 属性,在提交表单之后 response 返回到 iframe 中。form 的 action 可以自己写,也可以直接利用 富文本编辑器的接口实现上传

<form id="form_img" method="post" action="/Ueditor/net/controller.ashx?action=uploadimage" enctype="multipart/form-data" target="target_img">
        <div>选择图片封面:</div>
        <input id="img_file" accept="image/*" name="upfile" type="file" />
        <input name="submit" value="上传" type="submit" />
    </form>
    <iframe id="target_img" name="target_img" style="display:none"></iframe>
    <img id="pre_img" src="/Manage/images/no_face.gif" style="width:240px;height:155px" />

    <script>

        $(function ($) {
            var result;
            //这里注意 jquery 的版本
            $("#target_img").load(function () {
            //$("#target_img").on('load', function () {
                result = $(this);
                //console.log(result[0].contentDocument.body.textContent);
                var ans = JSON.parse(result[0].contentDocument.body.textContent);
                if (ans["state"] == "SUCCESS") {
                    alert("上传成功");
                    $("#pre_img").attr("src", "/Uploads/" + ans["url"]);
                    //结果保存在 父窗口的控件中
                    $('#face_img', parent.document).val("/Uploads/" + ans["url"]);
                }
                else {
                    alert("上传失败请重试!");
                }
            });
        });
    </script>


本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_1968