Html输入文件类型点击事件仅触发一次

时间:2015-08-14 18:12:06

标签: javascript html file input click

我想允许用户只选择一个zip文件。如果没有,我会显示一个带有一些消息的alert(),然后重新打开文件选择对话框窗口。我无法通过触发"点击"以第二次编程方式打开文件选择窗口。第二次输入元素上的事件。有什么想法吗?

http://jsfiddle.net/hanislovingit/40fcdtq8/



        var MAX_FILE_SIZE = 300 * 1024 * 1024; // 300 MB
        var ZIP_FILE_TYPE = "application/x-zip-compressed";

        var fileSelect = document.getElementById("fileSelect"),
          fileInputElem = document.getElementById("fileInputElem");

        fileInputElem.addEventListener("change", handleFiles, false);

        fileSelect.addEventListener("click", function(e) {
          if (fileInputElem) {
            fileInputElem.click();
          }

          e.preventDefault(); // prevent navigation to "#"
        }, false);


        function handleFiles() {

          if (this.files.length > 1) {
            window.alert("Only one file may be uploaded at a time.");
            fileInputElem.click();

          } else {
            var file = this.files[0];

            if (file.type !== ZIP_FILE_TYPE) {
              window.alert("File(s) must be zipped before uploading. Please zip files and try again. File type is " + file.type);
              fileInputElem.click();
            }

            if (file.size > MAX_FILE_SIZE) {
              window.alert("The file size exceeds the limit allowed and cannot be uploaded: " + file.size);
            }
          }

        }

<input type="file" id="fileInputElem" multiple style="display: none;" />
<a href="#" id="fileSelect">BROWSE FILES</a>
&#13;
&#13;
&#13;

0 个答案:

没有答案