0
点赞
收藏
分享

微信扫一扫

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


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

SAP UI5 FileUploader 使用的隐藏 iframe 和 form 元素的设计明细_SAP UI5

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

SAP UI5 FileUploader 使用的隐藏 iframe 和 form 元素的设计明细_ui5_02

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

SAP UI5 FileUploader 使用的隐藏 iframe 和 form 元素的设计明细_前端开发_03

SAP UI5 FileUploader 使用的隐藏 iframe 和 form 元素的设计明细_前端开发_04

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

SAP UI5 FileUploader 使用的隐藏 iframe 和 form 元素的设计明细_前端开发_05

关于 form 的 target 属性:

  • target 属性指定一个名称或关键字,指示在哪里显示提交表单后收到的响应。
  • 目标属性定义浏览上下文(例如选项卡、窗口或内联框架)的名称或关键字。

target 的值可能有以下几种:

SAP UI5 FileUploader 使用的隐藏 iframe 和 form 元素的设计明细_SAP UI5_06

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 awesome
this.$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;

},


举报

相关推荐

0 条评论