为了账号安全,请及时绑定邮箱和手机立即绑定

上传之前可以检查图像尺寸吗?

上传之前可以检查图像尺寸吗?

开心每一天1111 2019-11-14 14:44:26
我有一个用于将图像上传到服务器的上传控件,但是在上传之前,我只想确保图像尺寸正确。客户端上有什么可以用javascript完成的吗?
查看完整描述

3 回答

?
慕丝7291255

TA贡献1859条经验 获得超6个赞

您可以在提交表单之前检查它们:


window.URL = window.URL || window.webkitURL;


$("form").submit( function( e ) {

    var form = this;

    e.preventDefault(); //Stop the submit for now

                                //Replace with your selector to find the file input in your form

    var fileInput = $(this).find("input[type=file]")[0],

        file = fileInput.files && fileInput.files[0];


    if( file ) {

        var img = new Image();


        img.src = window.URL.createObjectURL( file );


        img.onload = function() {

            var width = img.naturalWidth,

                height = img.naturalHeight;


            window.URL.revokeObjectURL( img.src );


            if( width == 400 && height == 300 ) {

                form.submit();

            }

            else {

                //fail

            }

        };

    }

    else { //No file was input or browser doesn't support client side reading

        form.submit();

    }


});

这仅适用于现代浏览器,因此您仍然必须在服务器端检查尺寸。您也不能信任客户端,因此这是您仍然必须在服务器端检查它们的另一个原因。


查看完整回答
反对 回复 2019-11-14
?
神不在的星期二

TA贡献1963条经验 获得超6个赞

可能会晚一点,但这是使用promise接受的答案的现代ES6版本


const getUploadedFileDimensions: file => new Promise((resolve, reject) => {

    try {

        let img = new Image()


        img.onload = () => {

            const width  = img.naturalWidth,

                  height = img.naturalHeight


            window.URL.revokeObjectURL(img.src)


            return resolve({width, height})

        }


        img.src = window.URL.createObjectURL(file)

    } catch (exception) {

        return reject(exception)

    }

})

你会这样称呼它


getUploadedFileDimensions(file).then(({width, height}) => {

    console.log(width, height)

})


查看完整回答
反对 回复 2019-11-14
  • 3 回答
  • 0 关注
  • 438 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信