获取上传图像的宽度(在将文件上传到服务器之前)

时间:2014-02-23 11:50:27

标签: javascript jquery html forms

我有一些代码,我改变了。获得文件分机是正常的。我想要获得上传图像的宽度(甚至在点击提交输入之前),如果它太小而提供警报。问题是我真的不知道如何用html格式连接这个js代码。

<form id="add" method="POST" enctype="multipart/form-data" action="upload.php">
<input type="file" id= "filput" style="margin-bottom:30px; margin-top:20px;" name="file" size="40" />
</form>


$("#filput").on('change', function () {
    var w = $(this).width();
    if (w < 500) {
        alert("too small");
    } else {
        alert("big");
    }
});

1 个答案:

答案 0 :(得分:2)

this指的是输入而不是图像。您也使用HTML5文件API。

您可以使用此示例:How to get the image width from html 5 file API

代码示例:从Getting Image Dimensions using Javascript File API

复制
$("#filput").on('change', function () {
     var fr = new FileReader;

    fr.onload = function() { // file is loaded
        var img = new Image;

        img.onload = function() {
            alert(img.width); // image is loaded; sizes are available
        };

        img.src = fr.result; // is the data URL because called with readAsDataURL
    };

    fr.readAsDataURL(this.files[0]); // I'm using a <input type="file"> for demonstrating
});