开发者

Check input file for correct format with jquery

I use this code http://jsbin.com/uboqu3/83/edit#source

 function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah')
                    .attr('src', e.target.result)
                    .width(180);
            };

            reader.readAsDataURL(input.files[0]);
        }
    }

I need to check with jquery for correct format. For example if pictures have got jpg开发者_如何学JAVA than everything is ok and function show picture whitch will be uoloaded. If pictures --> gif, png tahn show alert or div message , input type=file wiill be reset and no picture will be shown. Can someone halp me with this.


You can simply check that the filename has an extension different from jpg:

function readURL(input) {
    if (input.files && input.files[0]) {
        //Check the extension
        if(!(/\.jpe?g$/i).test(input.files[0].name)) return alert('Error');
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah')
                .attr('src', e.target.result)
                .width(180);
        };

        reader.readAsDataURL(input.files[0]);
    }
}


Try this

function readURL(input) {
        if (input.files && input.files[0]) {
            var fileName = input.files[0];
            if(fileName.toLowerCase().indexOf(".jpg") == -1){
               alert("Invalid image file");
               return;
            }
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah')
                    .attr('src', e.target.result)
                    .width(180);
            };

            reader.readAsDataURL(input.files[0]);
        }
    }


A more reliable approach is to check the file type. I.e.:

function readURL(input) {
        if (input.files && input.files[0]) {
            var fileName = input.files[0];
            if(fileName.type != "image/jpeg"){
               alert("Invalid image file");
               return;
            }
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah')
                    .attr('src', e.target.result)
                    .width(180);
            };

            reader.readAsDataURL(input.files[0]);
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜