简体   繁体   English

如何让 jQuery 在上传时限制文件类型?

[英]How to have jQuery restrict file types on upload?

I would like to have jQuery limit a file upload field to only jpg/jpeg, png, and gif.我想让 jQuery 将文件上传字段限制为仅 jpg/jpeg、png 和 gif。 I am doing backend checking with PHP already.我已经在使用PHP进行后端检查。 I am running my submit button through a JavaScript function already so I really just need to know how to check for the file types before submit or alert.我已经通过JavaScript function 运行我的提交按钮,所以我真的只需要知道如何在提交或警告之前检查文件类型。

You can get the value of a file field just the same as any other field.您可以获得与任何其他字段相同的文件字段的值。 You can't alter it, however.但是,您无法更改它。

So to superficially check if a file has the right extension, you could do something like this:因此,要从表面上检查文件是否具有正确的扩展名,您可以执行以下操作:

var ext = $('#my_file_field').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
    alert('invalid extension!');
}

No plugin necessary for just this task.仅此任务不需要插件。 Cobbled this together from a couple other scripts:从其他几个脚本拼凑起来:

$('INPUT[type="file"]').change(function () {
    var ext = this.value.match(/\.(.+)$/)[1];
    switch (ext) {
        case 'jpg':
        case 'jpeg':
        case 'png':
        case 'gif':
            $('#uploadButton').attr('disabled', false);
            break;
        default:
            alert('This is not an allowed file type.');
            this.value = '';
    }
});

The trick here is to set the upload button to disabled unless and until a valid file type is selected.这里的技巧是将上传按钮设置为禁用,除非并且直到选择了有效的文件类型。

You could use the validation plugin for jQuery: http://docs.jquery.com/Plugins/Validation您可以使用 jQuery 的验证插件: http://docs.jquery.com/Plugins/Validation

It happens to have an accept() rule that does exactly what you need: http://docs.jquery.com/Plugins/Validation/Methods/accept#extension它恰好有一个 accept() 规则,可以满足您的需要: http://docs.jquery.com/Plugins/Validation/Methods/accept#extension

Note that controlling file extension is not bullet proof since it is in no way related to the mimetype of the file.请注意,控制文件扩展名不是防弹的,因为它与文件的 mimetype 没有任何关系。 So you could have a.png that's a word document and a.doc that's a perfectly valid png image.因此,您可以拥有一个 word 文档的 a.png 和一个完全有效的 png 图像的 a.doc。 So don't forget to make more controls server-side;)所以不要忘记在服务器端制作更多控件;)

For the front-end it is pretty convenient to put ' accept ' attribute if you are using a file field.对于前端,如果您使用的是文件字段,则放置“接受”属性非常方便。

Example:例子:

<input id="file" type="file" name="file" size="30" 
       accept="image/jpg,image/png,image/jpeg,image/gif" 
/>

A couple of important notes:几个重要的注意事项:

Don't want to check rather on MIME than on whatever extention the user is lying?不想检查 MIME 而不是用户撒谎的任何扩展? If so then it's less than one line:如果是这样,那么它少于一行:

<input type="file" id="userfile" accept="image/*|video/*" required />

for my case i used the following codes:对于我的情况,我使用了以下代码:

    if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test(fileName)) {              
    alert('You must select an image file only');               
    }

I try to write working code example, I test it and everything works.我尝试编写工作代码示例,我对其进行测试并且一切正常。

Hare is code:野兔是代码:

HTML: HTML:

<input type="file" class="attachment_input" name="file" onchange="checkFileSize(this, @Model.MaxSize.ToString(),@Html.Raw(Json.Encode(Model.FileExtensionsList)))" />

Javascript: Javascript:

 //function for check attachment size and extention match
function checkFileSize(element, maxSize, extentionsArray) {
    var val = $(element).val(); //get file value

    var ext = val.substring(val.lastIndexOf('.') + 1).toLowerCase(); // get file extention 
    if ($.inArray(ext, extentionsArray) == -1) {
        alert('false extension!');
    }

    var fileSize = ($(element)[0].files[0].size / 1024 / 1024); //size in MB
    if (fileSize > maxSize) {
        alert("Large file");// if Maxsize from Model > real file size alert this
    }
}

If you're dealing with multiple (html 5) file uploads, I took the top suggested comment and modified it a little:如果您正在处理多个 (html 5) 文件上传,我会采用最上面的建议评论并对其进行一些修改:

    var files = $('#file1')[0].files;
    var len = $('#file1').get(0).files.length;

    for (var i = 0; i < len; i++) {

        f = files[i];

        var ext = f.name.split('.').pop().toLowerCase();
        if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
            alert('invalid extension!');

        }
    }

This code works fine, but the only issue is if the file format is other than specified options, it shows an alert message but it displays the file name while it should be neglecting it.此代码工作正常,但唯一的问题是如果文件格式不是指定的选项,它会显示一条警告消息,但它会显示文件名,而它应该忽略它。

$('#ff2').change(
                function () {
                    var fileExtension = ['jpeg', 'jpg', 'pdf'];
                    if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                        alert("Only '.jpeg','.jpg','.pdf' formats are allowed.");
                        return false; }
});

This example allows to upload PNG image only.此示例仅允许上传 PNG 图像。

HTML HTML

<input type="file" class="form-control" id="FileUpload1" accept="image/png" />

JS JS

$('#FileUpload1').change(
                function () {
                    var fileExtension = ['png'];
                    if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                        alert("Only '.png' format is allowed.");
                        this.value = ''; // Clean field
                        return false;
                    }
                });
<form enctype="multipart/form-data">
   <input name="file" type="file" />
   <input type="submit" value="Upload" />
</form>
<script>
$('input[type=file]').change(function(){
    var file = this.files[0];
    name = file.name;
    size = file.size;
    type = file.type;
    //your validation
});
</script>
    $("input[name='btnsubmit']").attr('disabled', true);
    $('input[name="filphoto"]').change(function () {
    var ext = this.value.match(/\.(.+)$/)[1];
    switch (ext) 
    {
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'bmp':
        $("input[name='btnsubmit']").attr('disabled', false);
    break;
    default:
        alert('This is not an allowed file type.');
        $("input[name='btnsubmit']").attr('disabled', true);
        this.value = '';
function validateFileExtensions(){
        var validFileExtensions = ["jpg", "jpeg", "gif", "png"];
        var fileErrors = new Array();

        $( "input:file").each(function(){
            var file = $(this).value;
            var ext = file.split('.').pop();
            if( $.inArray( ext, validFileExtensions ) == -1) {
                fileErrors.push(file);
            }
        });

        if( fileErrors.length > 0 ){
            var errorContainer = $("#validation-errors");
            for(var i=0; i < fileErrors.length; i++){
                errorContainer.append('<label for="title" class="error">* File:'+ file +' do not have a valid format!</label>');
            }
            return false;
        }
        return true;
    }

Here is a simple code for javascript validation, and after it validates it will clean the input file.这是 javascript 验证的简单代码,验证后它将清理输入文件。

<input type="file" id="image" accept="image/*" onChange="validate(this.value)"/>

function validate(file) {
    var ext = file.split(".");
    ext = ext[ext.length-1].toLowerCase();      
    var arrayExtensions = ["jpg" , "jpeg", "png", "bmp", "gif"];

    if (arrayExtensions.lastIndexOf(ext) == -1) {
        alert("Wrong extension type.");
        $("#image").val("");
    }
}

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

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