【问题标题】:HTML5 Form Check image width and height and alert if biggerHTML5 表单检查图像宽度和高度,如果更大则发出警报
【发布时间】:2016-11-20 12:45:12
【问题描述】:

编辑

不是重复的

如果文件尺寸较大而不是尺寸较大,则需要停止表单提交。其他帖子中的一些答案是关于文件大小的,我的问题是关于尺寸的。大小和尺寸是两个不同的东西...

我正在使用以下表格上传图片。它工作正常,但因为它是一家商店,我希望产品目录看起来不错,所以我需要上传的图像正好是 200 像素宽和 200 像素高。如果图片的宽度或高度较大,我需要显示警报,以便上传者选择另一张图片或编辑他尝试上传的图片。

<form action="upload" enctype="multipart/form-data" method="post">

    Upload image:
    <input id="image-file" type="file" name="file" />
    <input type="submit" value="Upload" />

    <script type="text/javascript">
        $('#image-file').bind('change', function() {
            alert('here we have to do something');
        });
    </script>

</form>

【问题讨论】:

标签: javascript jquery css html


【解决方案1】:

可能重复?取自此处的答案并适合您:

Is it possible to check dimensions of image before uploading?

我同意上述答案并在提交表单上执行:

$( document ).ready(function() {
$("#ImageForm").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("#image-file")[0],
        file = fileInput.files && fileInput.files[0];
	console.log(file)
    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 <= 200 && height <= 200) {
                form.submit();
            }
            else {
                alert('too big');
            }
        };
    }
    else { //No file was input or browser doesn't support client side reading
        form.submit();
    }

});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="ImageForm" method="post">

    Upload image:
    <input id="image-file" type="file" name="file" />
    <input type="submit" value="Upload" />
</form>

正如我链接中的答案所说,您还需要检查此服务器端,因为 a) 您永远无法信任客户端 b) 较旧的浏览器可能无法工作。

【讨论】:

  • 好像只有你知道检查文件大小和检查宽高之间的区别...我会试一试
  • 没有工作我用 Chrome 测试并且表单提交时没有警告
  • 已修复。我会在没有'#'的情况下弄乱 $("#ImageForm") 选择器。 Js 小提琴jsfiddle.net/uL1xgjbp/1
  • 我已将其更改为
  • 它工作得几乎完美,所以我将您的解决方案标记为正确。
猜你喜欢
  • 2011-08-28
  • 2017-08-09
  • 1970-01-01
  • 2018-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-04
相关资源
最近更新 更多