SAP UI5 FileUploader 的本地文件上传技术实现分享

当我们使用 SAP UI5 的 FileUploader 控件,上传本地文件时,其执行逻辑的入口,就是 FileUploader.prototype.upload

首先判断该控件是否已经被 disable:

if (!this.getEnabled()) {
    
    
			return;
		}

SAP UI5 FileUploader 底层可以基于 form 的 multipart/form-data 或者 XHR 两种技术方式进行文件上传,这在下面的源代码看得很清楚。

首先使用 getDomRef 获取 fu_form,即下图这个高亮区域:

try {
    
    
			this._bUploading = true;
			if (this.getSendXHR() && window.File) {
    
    
				var aFiles = this.FUEl.files;
				if (bPreProcessFiles) {
    
    
					this._sendProcessedFilesWithXHR(aFiles);
				} else {
    
    
					this._sendFilesWithXHR(aFiles);
				}
			} else if (uploadForm) {
    
    
				// In order to do the submit, the action DOM attribute of the inner form should be accurate.
				// If there is a change in the passed to the uploadUrl property string, we must ensure that it is
				// applied in the DOM and the submit is performed after there is new rendering.
				sActionAttr = uploadForm.getAttribute("action");
				if (sActionAttr !== this.getUploadUrl()) {
    
    
					this._submitAfterRendering = true;
				} else {
    
    
					this._submitAndResetValue();
				}
			}

如果返回的对象实例不为空,说明使用 form 的方式去提交本地代码。

此时准备提交文件了:_submitAndResetValue

调用的是 HTML form 原生的 submit 方法进行提交:

服务器端返回了一个 File uploaded ok! 的字符串:

这个字符串在隐藏的 iframe 里能够看到:

访问不了 this.oIFrameRef.contentWindow.document.body.innerHTML;

错误消息:VM1992:1 Uncaught DOMException: Blocked a frame with origin “http://localhost:8080” from accessing a cross-origin frame.

不能使用 JavaScript 访问具有不同来源的 iframe,以避免任何可能的安全风险。 对于同源策略,浏览器会阻止脚本尝试访问具有不同源的 iframe.

实际上,我根本就不能在 8080 端口的 index.html 上下文环境里,查看另一个 iframe 的任何属性,报一样的错误:

那我提前在 iframe 创建时检测:

刚刚创建出的 iframe,href 是 about:blank:

直到这个函数执行完,this.oIFrameRef.contentWindow.location.href 都是处于可访问状态:

beforeRendering 的钩子里,this.oIFrameRef.contentWindow.location.href 仍然可用,但是 afterRendering 的钩子就不行了:

这个 before 和 afterRendering 的钩子,在点击 Browse… 按钮选择本地文件的时候,会各触发一次。

选定好之后,点击 Upload 按钮,会再触发一次:

点击 upload File 之后,执行 submit 之前,都可以正常访问:this.oIFrameRef.contentWindow.location.href

post 到 3003 之后,再访问就不行了:

猜你喜欢

转载自blog.csdn.net/i042416/article/details/126012470