在上传之前是否可以检查图像的尺寸?

Sab*_*y62 62 javascript jquery file-upload client-side

我有一个上传控件用于将图像上传到服务器,但在上传之前我只想确保图像的尺寸是否正确.客户端是否可以使用javascript完成任何操作?

Esa*_*ija 66

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

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

});
Run Code Online (Sandbox Code Playgroud)

这仅适用于现代浏览器,因此您仍需检查服务器端的尺寸.您也无法信任客户端,因此无论如何您必须检查服务器端的另一个原因.


Gur*_*ngh 48

是的,HTML5 API支持这一点.

http://www.w3.org/TR/FileAPI/

var _URL = window.URL || window.webkitURL;

$("#file").change(function(e) {

    var image, file;

    if ((file = this.files[0])) {

        image = new Image();

        image.onload = function() {

            alert("The image width is " +this.width + " and image height is " + this.height);
        };

        image.src = _URL.createObjectURL(file);


    }

});?
Run Code Online (Sandbox Code Playgroud)

演示(在铬上测试)

  • @AlienWebguy - 当然是,看到这个[**SITE**](http://base64img.com),在删除或选择图像时,名称,文件大小和尺寸会立即更新,而不会将图像上传到服务器. (2认同)