打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
SAP UI5 FileUploader 使用的隐藏 iframe 和 form 元素的设计明细
userphoto

2022.07.30 四川

关注

我们研究 SAP UI5 FileUploader 控件渲染时生成的 HTML 源代码:真正提供给用户选择文件上传的控件,是下图高亮的这个类型属性 type 为 file 的 input 控件。

这个 file input 位于下图高亮的 form 控件,该控件的 action 指向文件服务器 url:http://localhost:3003/upload, 即接收文件上传的服务器。 target 指向另一个隐藏 iframe 的 id:

这个隐藏的 iframe 如下图所示:

这个 iframe 位于 SAP UI5 框架的 static area 内:

关于 form 的 target 属性:

  • target 属性指定一个名称或关键字,指示在哪里显示提交表单后收到的响应。

  • 目标属性定义浏览上下文(例如选项卡、窗口或内联框架)的名称或关键字。

target 的值可能有以下几种:

SAP UI5 使用的是最后一种,指向一个通过 id 属性指明的 iframe.

form 的 action 属性:提交表单时将表单数据发送到哪里。

可能的值:

  • 绝对 URL - 指向另一个网站(如 action="http://www.example.com/example.htm")

  • 相对 URL - 指向网站内的文件(如 action="example.htm")

SAP UI5 XML 视图里建议使用第二种,更加灵活。

有的开发者可能觉得疑惑,为什么在文件上传的场景里,需要一个隐藏的 iframe?实际上,我们需要一个 iframe 在不离开当前页面的情况下上传文件(比如 Ajax).

现代浏览器支持 FormData,它允许开发者使用 XMLHttpRequest 上传文件。

总结

使用 iframe + input 进行文件上传的步骤。首先定义 form 和 iframe 元素:

<div id='status'></div><form id="file-upload-form" name="file-upload-form">
   <input type="file" id="upload-doc-file" name="upload-doc-file"></form><iframe id="postiframe" name="postiframe"></iframe>

将 form 的 target 属性指定为 iframe 的 id,下面的例子是 postiframe,这样通过 file input 上传文件时,不会强制让当前页面刷新。

iframeSubmitFile: function() {//adds a spinning loading icon.  Icon is from font awesomethis.$el.find("#status").html("<i class='icon-spinner icon-spin loading'> </i>");

        var form = $('#file-upload-form');
        form.attr("action", "/user-upload-doc");
        form.attr("method", "post");
        form.attr("enctype", "multipart/form-data");
        form.attr("target", "postiframe");
        //form.attr("target", iframe);        form.attr("file", this.$el.find('#upload-doc-file').val());

        //example of how to add another value to the post field        var audit_id = 5;
        //dynamically create an input value for the form post        var audit_id_input = $("<input>").attr("type", "hidden").attr("name", "audit_id").val(audit_id);

        //add it to the form        form.append($(audit_id_input));

        //submit form        form.submit();

        this.refreshUploadAction(); //reset the upload box
        this.$el.find("#postiframe").load(function() {

             //removes the loading icon because the file has finished uploading            $("#status").html("");

            //having trouble getting the results back from the post            // console.log($("#postiframe"))            //  iframeContents = $("#postiframe")[0].contentWindow.document.body.innerHTML;            //  console.log(iframeContents)            // $("#textarea").html(iframeContents);        });

        return false;

    },
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
jquery改变form提交属性
LAYUI -下拉多选效果
js设置form表单内元素为只读属性
iframe中子页和父页面如何传值
jquery 使用post方式下载
文件上传的渐进式增强
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服