正在开发自定义文件上传应用程序。我有两个主要问题:
- 下面给出的代码不是打开 Mozilla 和 IE 的文件对话框。
- 在 Chrome 中它可以工作,但是当我在第一次单击时选择"file"时,它永远不会将文件添加到正文中。但在第二次单击时,它将在第一次单击时浏览的文件添加到正文中。
对于上述问题的任何帮助,我们将不胜感激。
function perform1Click(node) { alert("INIT"); var evt = document.createEvent("MouseEvents"); evt.initEvent("click", true, false); node.dispatchEvent(evt); alert(3) getFile(evt); } function getFile(event) { var files = event.target.files; var totalSize = 0; if (totalSize > 1024*10) { alert('Total size exceed 1 Mb.'); return; } //alert(files) //alert(files.length); for (var i = 0, f; f = files[i]; i++) { displayFileList(f.name, f.size); totalSize = totalSize+f.size; } } function displayFileList(name, size) { if (name != '') { var top_plugin = document.getElementById('top_plugin'); // create tag var ptag = document.createElement("p"); // create div var divBox = document.createElement("div"); divBox.setAttribute('class', 'divBox'); // create input[type='checkbox'] var inputCheckBox = document.createElement("input"); inputCheckBox.setAttribute('type', 'checkbox'); inputCheckBox.setAttribute('id', 'checkboxClass') // add checkbox to div. divBox.appendChild(inputCheckBox); // create text node for divBox and add it to divBox. var txtNode = document.createTextNode(name); divBox.appendChild(txtNode) var sizeDivBox = document.createElement("p"); sizeDivBox.setAttribute('style', 'clear:both; display: inline-block;'); var txtSizeNode = document.createTextNode(size); sizeDivBox.appendChild(txtSizeNode); divBox.appendChild(sizeDivBox); // add divBox to ptag. ptag.appendChild(divBox); //ptag.appendChild(divTxt); // add ptag to top_plugin div. top_plugin.appendChild(ptag); } // if file value is not null, make it blank. if (name != '') { name = ''; } }
最佳答案
我得到了同样问题的解决方案。请在下面找到新代码。
function uploadDFiles() {
var file = document.getElementById('_file');
file.click();
try {
file.addEventListener("change", getFileName);
}
catch (e) {
file.attachEvent("onclick", getFileNameOnIE);
alert("Error:: "+e.description);
}
}
function getFileName(event) {
var files = event.target.files;
for (var i = 0, f; f = files[i]; i++) {
var fileName = f.name;
var fileSize = f.size;
var fSize = bytesToSize(fileSize, 2);
displayFileList(fileName, fSize);
}
}
但是现在我遇到了新问题。此代码在 IE 中不起作用。对于 IE,我使用 AttachEvent 方法,但它不起作用。请找到下面的代码:
function getFileNameOnIE(event) {
alert(event.type);
var files = event.target;
alert(files.length);
for (var i = 0, f; f = files[i]; i++) {
displayFileList(f.name, f.size);
}
}
现在有人可以为我提供同样的解决方案吗?
--
谢谢 巴拉特
关于Javascript DOM 鼠标事件不适用于 IE 和 Mozilla,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10010077/