asp.net – 在文件上传期间使用Javascript获取图像尺寸
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了asp.net – 在文件上传期间使用Javascript获取图像尺寸,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2349字,纯文字阅读大概需要4分钟。
内容图文
![asp.net – 在文件上传期间使用Javascript获取图像尺寸](/upload/InfoBanner/zyjiaocheng/715/b6538a1f8ff24fc5a0050f8c0e1724db.jpg)
我有文件上传UI元素,用户将在其中上传图像.在这里,我必须验证客户端图像的高度和宽度.是否有可能在JS中找到只有文件路径的图像大小?
注意:如果否,是否有其他方法可以在客户端找到维度?
解决方法:
您可以在支持W3C的新File API的浏览器上执行此操作,使用FileReader界面上的readAsDataURL函数并将数据URL分配给img的src(之后您可以读取图像的高度和宽度).目前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)样式事件处理程序等道歉.
内容总结
以上是互联网集市为您收集整理的asp.net – 在文件上传期间使用Javascript获取图像尺寸全部内容,希望文章能够帮你解决asp.net – 在文件上传期间使用Javascript获取图像尺寸所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。