今天我为大家带来一个无刷新提交表单图片,然后从新生成本地图片。
在一次工作中做了一个这样的功能,

由上图看出,利用DOM做了一个图片编辑UI。
流程:
当触发编辑时候调用JS生成IFRAME窗口并且生成表单上传所有DOM
自动触发子窗口上传功能
//图片上传
doc.getElementById("imgEdit").onclick = function(){
img_edit();
}
//图片编辑
function img_edit(){
var ifarme = doc.createElement("iframe");
ifarme.setAttribute("id","iframeImg");
doc.body.appendChild(ifarme);
//doc.getElementById("iframeImg").style.display = "none";
var imgForm = doc.createElement("form");
imgForm.setAttribute("action","test.php"); //设置img提交地址
imgForm.setAttribute("method","post");
imgForm.setAttribute("enctype","multipart/form-data");
ifarme.contentWindow.document.body.appendChild(imgForm);
iframeFormObj = ifarme.contentWindow.document.getElementsByTagName('form')[0];
var img = doc.createElement("input");
img.type = "file";
img.name = "imgUpload";
img.id = "imgUpload";
imgForm.appendChild(img);
var ev = doc.createEvent('MouseEvents');
// initMouseEvent的参数比较多,可以参见API文档
// https://developer.mozilla.org/en-US/docs/Web/API/event.initMouseEvent
ev.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
ifarme.contentWindow.document.getElementById('imgUpload').dispatchEvent(ev);
img.onchange = function(){
iframeFormObj.submit();
//document.body.removeChild(ifarme);
}
//提交后,页面执行以下JS
//window.parent.document.getElementById('imgFile').value = "结果";
//window.parent.document.getElementById('imgFace').setAttribute("src","结果");
}



