【问题标题】:get width of uploaded image (before uploading file to server)获取上传图像的宽度(在将文件上传到服务器之前)
【发布时间】:2014-03-24 22:30:59
【问题描述】:

我有一些我更改的代码。以前是获取文件分机。我希望它获得上传图像的宽度(甚至在单击提交输入之前),如果它太小,则发出警报。问题是我真的不知道如何将这个 js 代码与 html 表单连接起来。

<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");
    }
});

【问题讨论】:

  • $(this) 在您的“更改”处理程序中指的是 #filput 元素,而不是您上传的图像。

标签: javascript jquery html forms


【解决方案1】:

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
});

【讨论】:

  • 我不鼓励您使用 FileReader 来完成此任务。您冒着耗尽浏览器内存的风险,更不用说这是一个非常低效的操作,尤其是在涉及大文件时。相反,使用 URL.createObjectURL,传入文件或 blob。然后,将此调用的结果设置为 img 的 src attr。
猜你喜欢
  • 1970-01-01
  • 2015-06-29
  • 2012-01-19
  • 2011-10-08
  • 1970-01-01
  • 2016-06-06
  • 2012-09-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多