我有一个文件上传的UI元素,用户将上传图像。在这里,我必须在客户端验证图像的高度和宽度。是否有可能使用JS仅通过文件路径查找图像的大小?
注意:如果不行,是否有其他方法可以在客户端找到图像的尺寸?
我有一个文件上传的UI元素,用户将上传图像。在这里,我必须在客户端验证图像的高度和宽度。是否有可能使用JS仅通过文件路径查找图像的大小?
注意:如果不行,是否有其他方法可以在客户端找到图像的尺寸?
FileReader
接口上的readAsDataURL
函数,并将数据 URL 分配给 img
的 src
(之后您可以读取图像的 height
和 width
)。目前 Firefox 3.6 支持 File API,我认为 Chrome 和 Safari 要么已经支持,要么即将支持。
因此,在过渡阶段,您的逻辑应该是这样的:
检测浏览器是否支持 File API(很容易: if (typeof window.FileReader === 'function')
)。
如果支持,那就太好了,可以在本地读取数据并将其插入到图像中以查找其尺寸。
如果不支持,则将文件上传到服务器(可能会从 iframe 提交表单以避免离开页面),然后轮询服务器询问图像的大小(或者只是请求已上传的图像,如果您喜欢的话)。
编辑 我一直想制作一个文件 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]);
HTML5 绝对是这里的正确解决方案。 你应该始终为未来编写代码,而不是过去。 处理 HTML4 浏览器的最佳方法是要么回退到降级功能,要么使用 Flash(但仅在浏览器不支持 HTML5 文件 API 的情况下)
使用 img.onload 事件将使您能够恢复文件的尺寸。 它正在我正在开发的应用程序中工作。