0

我正在使用 ASP.NET C# 4.0,我的 Web 表单由用于上传图像的输入类型文件组成。

我需要在客户端验证图像,然后再将其保存到我的 SQL 数据库

因为我使用输入类型=文件来上传图像,所以我不想发回验证图像大小、尺寸的页面。

需要你的帮助 谢谢

4

2 回答 2

3

你可以做这样的事情......

您可以在支持W3C的新文件 APIreadAsDataURL的浏览器上执行此操作,使用界面上的函数FileReader并将数据 URL 分配给srcan img(之后您可以读取图像的heightand width)。目前 Firefox 3.6 支持 File API,我认为 Chrome 和 Safari 要么已经支持,要么即将支持。

所以你在过渡阶段的逻辑是这样的:

  1. 检测浏览器是否支持 File API(很简单:)if (typeof window.FileReader === 'function')

  2. 如果是这样,很好,在本地读取数据并将其插入图像中以查找尺寸。

  3. 如果不是,则将文件上传到服务器(可能从 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)样式事件处理程序等表示歉意。

于 2011-10-15T07:12:28.687 回答
1
function getImgSize(imgSrc) {
    var newImg = new Image();

    newImg.onload = function() {
    var height = newImg.height;
    var width = newImg.width;
    alert ('The image size is '+width+'*'+height);
    }

    newImg.src = imgSrc; // this must be done AFTER setting onload

}
于 2011-10-15T07:03:21.773 回答