Qix*_*Qix 8 javascript ajax file-upload xmlhttprequest
在IE9中,FormData不受支持,这使得使用上传文件XMLHttpRequest不那么简单.
可以这样做吗?我已经看过iFrames提到了,虽然我不反对编写一些毛茸茸的代码,但我不知道如何实现这一点(有很多资源在讨论上传到iFrame而不是如何获得从iFrame到服务器的文件).
使用vanilla JavaScript(没有第三方库),如何在不使用的情况下异步上传文件FormData?
这段代码应该可以解决问题.抱歉很久以前,我认为IE9也可以使用XHR上传(应该,但这是Iframe选项).
它执行以下操作:
fileSelection = document.createElement("div");
//create the file input
fileSelection.browseSelect = document.createElement("input");
fileSelection.browseSelect.type = "file";
fileSelection.browseSelect.name = "file[]";
fileSelection.browseSelect.style.display = "block";
fileSelection.browseSelect.style.position = "absolute";
fileSelection.browseSelect.style.left = "50%";
fileSelection.browseSelect.style.top = "auto";
fileSelection.browseSelect.style.height = "36px";
fileSelection.browseSelect.style.width = "36px";
fileSelection.browseSelect.style.bottom = "0px";
fileSelection.browseSelect.style.margin = "0px 0px -1px 90px";
fileSelection.browseSelect.style.filter = "alpha(opacity=0)";
fileSelection.browseSelect.style.zIndex = 14;
//Put a form in it.
fileSelection.form = document.createElement("form");
fileSelection.form.method = "POST";
fileSelection.form.action = [url to server]; //put your own file upload handler here.
fileSelection.form.enctype = "multipart/form-data";
fileSelection.form.encoding = "multipart/form-data";
fileSelection.appendChild(fileSelection.form);
//Append the file input to the form.
fileSelection.form.appendChild(fileSelection.browseSelect);
document.body.appendChild(fileSelection);
function doUploadObjectUpload()
{
var tempFrame = document.createElement("iframe");
tempFrame.src = "";
tempFrame.allowTransparancy = "true";
tempFrame.style.display = "none";
tempFrame.frameBorder = 0;
tempFrame.style.backgroundColor = "transparent";
tempFrame.onload = followUpOnHTML4Upload.bind(this,tempFrame);
tempFrame.name = "tmpFrameUpload"
this.appendChild(tempFrame);
this.form.target = tempFrame.name;
this.form.name = "uploadForm";
this.form.acceptCharset = "UTF-8"
//This is an example of a hidden input, used to pass extra vars to the server. Add more if you need them.
var tempNodePath = document.createElement("input");
tempNodePath.type = "hidden";
tempNodePath.value = [dir]; //if you want specify a target path.
tempNodePath.name = "filePath";
this.form.insertBefore(tempNodePath, this.form.childNodes[0]);
this.form.submit();
}
function followUpOnHTML4Upload(frameId)
{
//Here you can check the response that came back from the page.
}
Run Code Online (Sandbox Code Playgroud)
例如,PHP将存储文件 $_FILES
| 归档时间: |
|
| 查看次数: |
11865 次 |
| 最近记录: |