咱们钻研 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; },