简体   繁体   English

jQuery检查文件类型输入中的上传文件名

[英]Jquery checking the upload filename in file type input

I was trying to check the filename by the filename format given using JQuery.. 我试图通过使用JQuery给出的文件名格式检查文件名。

this is my code: 这是我的代码:

<input class="" name="myfile" id="myfile" type="file" multiple="false" data-value="">

my JQuery Script: 我的JQuery脚本:

function checkFileName(filename, file_id){
    var must_filename;

    must_filename = jQuery(file_id).attr('data-value').split('.').slice(0, 2).join('.');
    jQuery('.file_err_det').remove();
    alert(must_filename + ' != ' + filename);
    // filename value is always null?
    if(must_filename != filename){          
        alert('Filename is not valid! Please follow the format and upload it again');
        jQuery(file_id).val('');
    }
}

jQuery('#myfile').blur(function() {
    var this_filename = jQuery(this).val().split('.').slice(0, 2).join('.');
    checkFileName(this_filename, '#myfile');
    alert(this_filename); // this returns null? I dont know why..
});

but it seems the value this_filename is null. 但似乎值this_filename为null。 I am using blur , is there anything that I can use to check the jQuery('#myfile').val() ? 我正在使用blur ,有什么我可以用来检查jQuery('#myfile').val()吗?

See Using files from web applications 请参阅使用Web应用程序中的文件

The File API makes it possible to access a FileList containing File objects representing the files selected by the user. File API使访问包含代表用户所选文件的File对象的FileList成为可能。

If the user selects just one file, it is then only necessary to consider the first file of the list. 如果用户仅选择一个文件,则仅需考虑列表的第一个文件。

Accessing one selected file using a classical DOM selector: 使用经典的DOM选择器访问一个选定的文件:

var selectedFile = document.getElementById('input').files[0];

Accessing one selected file using a jQuery selector: 使用jQuery选择器访问一个选定的文件:

var selectedFile = $('#input').get(0).files[0];

var selectedFile = $('#input')[0].files[0];


Try utilizing change event 尝试利用变更事件

 $("#myfile").on("change", function(e) { var file = e.target.files[0]; console.log(file, file.name); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <input class="" name="myfile" id="myfile" type="file" multiple="false" data-value=""> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM