9

这是我的脚本。我想要做的是使用 onchange 事件触发它。但它似乎不太好用。我在这里和那里尝试过编辑,但仍然面临问题。至于我下面的最新编辑,问题是,有 2 个文件要上传,但只有第二个会显示警报消息,而第一个只会收到任何文件。

    <script>
    function checkFile()
    {   
    var node_list = document.getElementsByTagName('input');
    for (var i = 0; i < node_list.length; i++) 
    {
        var node = node_list[i];
        if (node.getAttribute('type') == 'file') 
        {
            var sFileName = node.value;
            var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1];
            var iFileSize = node.files[0].size;
            var iConvert=(node.files[0].size/10485760).toFixed(2);
        }


        if (sFileExtension != "pdf" && sFileExtension != "doc" && sFileExtension != "docx" && iFileSize>10485760)
        {   
            txt="File type : "+ sFileExtension+"\n\n";
            txt+="Size: " + iConvert + " MB \n\n";
            txt+="Please make sure your file is in pdf or doc format and less than 10 MB.\n\n";
            alert(txt);
        }
    }
}
    </script>

我的形式,

  <input type="file" name="file" id="confirm" onchange="checkFile()">
  <input type="file" name="file" id="approveletter" onchange="checkFile()">
4

8 回答 8

22

而不是依赖于它们自己的元素,您应该使用给定的函数事件来获取触发回调函数调用的文件。

传递事件将保证您实际上正在使用导致调用该函数的当前文件。

例如(我更改了变量名称以使其更清晰):

在线演示在这里

/// pass in event 
function checkFile(e) {

    /// get list of files
    var file_list = e.target.files;

    /// go through the list of files
    for (var i = 0, file; file = file_list[i]; i++) {

        var sFileName = file.name;
        var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();
        var iFileSize = file.size;
        var iConvert = (file.size / 1048576).toFixed(2);

        /// OR together the accepted extensions and NOT it. Then OR the size cond.
        /// It's easier to see this way, but just a suggestion - no requirement.
        if (!(sFileExtension === "pdf" ||
              sFileExtension === "doc" ||
              sFileExtension === "docx") || iFileSize > 10485760) { /// 10 mb
            txt = "File type : " + sFileExtension + "\n\n";
            txt += "Size: " + iConvert + " MB \n\n";
            txt += "Please make sure your file is in pdf or doc format and less than 10 MB.\n\n";
            alert(txt);
        }
    }
}
于 2013-09-20T07:20:35.783 回答
1

这可能会有所帮助

var file = document.getElementById("filex").files[0];
var filename = file.name;

var extSplit = filename.split('.');
var extReverse = extSplit.reverse();
var ext = extReverse[0];

if(!ext === "mp4" || !ext === "flv"){
  alert('Accepted');
} else {
  alert('Not accepted');
}
于 2015-01-11T12:17:37.150 回答
1

您可以将此代码与 html 中的文件控制器一起使用。任何只传递参数并查看输出

   <script type="text/javascript">
function AlertFilesize(cid,sz,a){
    var controllerID = cid;
    var fileSize = sz;
    var extation = a;
    if(window.ActiveXObject){
        var fso = new ActiveXObject("Scripting.FileSystemObject");
        var filepath = document.getElementById('fileInput').value;
        var thefile = fso.getFile(filepath);
        var sizeinbytes = thefile.size;
    }else{
        var sizeinbytes = document.getElementById('fileInput').files[0].size;
    }
    var fSExt = new Array('Bytes', 'KB', 'MB', 'GB');
    fSize = sizeinbytes; i=0;while(fSize>900){fSize/=1024;i++;}
    var fup = document.getElementById('fileInput');
    var fileName = fup.value;
    var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
    if(ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG")
    {   
        var fs = Math.round(fSize);
        if(fs < fileSize && fSExt[i] == extation)
        {
            alert("Image Successfully Uploaded");
            return true;}else{
            alert("Please enter the image size less then"+fileSize+extation);
            document.getElementById('fileInput').value='';
            return false;
            }
        }else{
        alert("Must be jpg and gif images ONLY");
        document.getElementById('fileInput').value='';
        return false;}
    }
</script>
<input id="fileInput" type="file" onchange="AlertFilesize(this.id,100,'KB');" />
于 2015-05-06T14:32:30.403 回答
1
<script type="text/javascript">
function setFileSize() {
        var fileEl = document.getElementById('<%=FileUpload1.ClientID%>');
        var fileSize = fileEl.files[0].size / 1024 / 1024;
        var fileName = fileEl.files[0].name;
        var dotPosition = fileName.lastIndexOf(".");
        var fileExt = fileName.substring(dotPosition);
        if (fileSize > 1) {
        fileEl.value = '';
            document.getElementById('<%=lblFileStatus.ClientID%>').innerHTML = 'File Should Be less Than 1MB';
            return false;
        }
}


于 2015-07-29T10:07:23.947 回答
0

http://jsfiddle.net/kVdT5/

看看这个小提琴。它工作得很好。正如我所说,您的 if 条件发生了变化。

if (sFileExtension != "pdf" && sFileExtension != "doc" && sFileExtension != "docx" && iFileSize>10485760)

用这个替换它

if ((sFileExtension != "pdf" && sFileExtension != "doc" && sFileExtension != "docx") || iFileSize>10485760))
于 2013-09-19T08:45:50.970 回答
0
    <!DOCTYPE html>
        <html>
        <body>

        <p>When you submit the form, a function is triggered which alerts some text.</p>

        <form action="demo_form.asp" id="form">
          Enter name: <input type="file" name="fname" id="form_file" onchange=" return myFunction()">
          <input type="submit" value="Submit" id="submit">
        </form>

        <script>
        function myFunction() {
             var file = document.getElementById("form_file");
             var file_name = file.value;
             var extension = file_name.split('.').pop().toLowerCase();
             var size      = file.files[0].size;
             var allowedFormats = ["jpeg", "jpg", "pdf", "tif"];

              if(!(allowedFormats.indexOf(extension) > -1)){
               alert("Enter a jpg/jpeg/pdf/tif file");

               document.getElementById("submit").disabled = true;
               return false;              
              } else if( ((size/1024)/1024) > 15){
                 alert("Your file should be less than 15MB");
                 return false;
              } else {
               document.getElementById("submit").disabled = false;   
              }
        }
        </script>
        </body>
        </html>
于 2016-08-23T06:28:14.333 回答
0

这是我的解决方案

function checkFile(field){
    let imagePath = field.value;
    let allowedExtensions = /(\.jpg|\.png|\.jpeg|\.JPG|\.PNG|\.JPEG|\.jPg|\.pNg|\.jPeg|\.jpG|\.pnG|\.jpEg|\.JPg|\.PNg|\.JPeg)$/i;
    if (field.files[0].size > (2 * 1048576)){ // 2 MB
        // size exceeds
    }else if (!allowedExtensions.exec(imagePath)) {
        // extensions does not match
    } else {
        // everything OK
    }
}
于 2021-01-20T16:02:42.377 回答
0

这是 JavaScript onchange 事件基础文件大小和类型验证脚本,可以在多个输入文件中使用

<input type="file" onchange="checkFile(this)" class="form-control" name="doc_file[]">
<script>
function checkFile(item){
    var extension = $(item).val().split('.').pop().toLowerCase();
// Create array with the files extensions that we wish to upload
    var validExtensions = ['jpeg', 'jpg', 'cdr', 'pdf', 'tiff'];
    //Check file extension in the array.if -1 that means the file extension is not in the list.
    if ($.inArray(extension, validExtensions) == -1) {
        $('#errormsg').text("Failed! Please upload jpg, jpeg, cdr, tiff, pdf file only.").show();
    // Clear fileuload control selected file
        $(item).replaceWith($(item).val('').clone(true));
    //Disable Submit Button
        $('#submit').prop('disabled', true);
    }
    else {
    // Check and restrict the file size to 32 KB.
        if ($(item).get(0).files[0].size > (20971520)) {
            $('#errormsg').text("Failed!! Max allowed file size is 20 MB").show();
        // Clear fileuload control selected file
            $(item).replaceWith($(item).val('').clone(true));
        //Disable Submit Button
            $('#submit').prop('disabled', true);
        }
        else {
        //Clear and Hide message span
            $('#errormsg').text('').hide();
        //Enable Submit Button
            $('#submit').prop('disabled', false);
        }
    }
};
</script>
于 2020-08-21T06:38:22.977 回答