Gop*_*opi 12 javascript asp.net validation file-upload image
我有文件上传UI元素,用户将在其中上传图像.在这里,我必须验证客户端图像的高度和宽度.是否有可能在JS中找到仅具有文件路径的图像大小?
注意:如果否,是否有其他方法可以在客户端查找维度?
T.J*_*der 21
为此,您可以在支持新的浏览器文件API从W3C,使用readAsDataURL该功能上的FileReader接口和分配数据URL到src的img(之后就可以读取height和width图像).目前Firefox 3.6支持File API,我认为Chrome和Safari已经或即将推出.
所以你在过渡阶段的逻辑是这样的:
检测浏览器是否支持File API(这很简单:) if (typeof window.FileReader === 'function').
如果确实如此,请在本地读取数据并将其插入图像中以查找尺寸.
如果没有,请将文件上传到服务器(可能是从iframe提交表单以避免离开页面),然后轮询服务器询问图像有多大(或者只是询问上传的图像,如果您愿意的话).
编辑我一直想在一段时间内编写一个File API的例子; 这是一个:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show Image Dimensions Locally</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript'>
    function loadImage() {
        var input, file, fr, img;
        if (typeof window.FileReader !== 'function') {
            write("The file API isn't supported on this browser yet.");
            return;
        }
        input = document.getElementById('imgfile');
        if (!input) {
            write("Um, couldn't find the imgfile element.");
        }
        else if (!input.files) {
            write("This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            write("Please select a file before clicking 'Load'");
        }
        else {
            file = input.files[0];
            fr = new FileReader();
            fr.onload = createImage;
            fr.readAsDataURL(file);
        }
        function createImage() {
            img = document.createElement('img');
            img.onload = imageLoaded;
            img.style.display = 'none'; // If you don't want it showing
            img.src = fr.result;
            document.body.appendChild(img);
        }
        function imageLoaded() {
            write(img.width + "x" + img.height);
            // This next bit removes the image, which is obviously optional -- perhaps you want
            // to do something with it!
            img.parentNode.removeChild(img);
            img = undefined;
        }
        function write(msg) {
            var p = document.createElement('p');
            p.innerHTML = msg;
            document.body.appendChild(p);
        }
    }
</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='imgfile'>
<input type='button' id='btnLoad' value='Load' onclick='loadImage();'>
</form>
</body>
</html>
适用于Firefox 3.6.我避免在那里使用任何库,所以对属性(DOM0)样式事件处理程序等道歉.
前面的例子是好的,但它远非完美.
var reader  = new FileReader();
reader.onload   = function(e)
{
    var image   = new Image();
    image.onload    = function()
    {
        console.log(this.width, this.height);
    };
    image.src   = e.target.result;
};
reader.readAsDataURL(this.files[0]);