【发布时间】:2009-10-16 10:52:12
【问题描述】:
有没有办法在上传到服务器之前验证图像大小(高度和宽度)?
我认为正在使用 Javascript,但我不知道如何。或者也许使用一些客户端 asp.net 验证器。
有什么建议吗?
【问题讨论】:
标签: c# asp.net image validation
有没有办法在上传到服务器之前验证图像大小(高度和宽度)?
我认为正在使用 Javascript,但我不知道如何。或者也许使用一些客户端 asp.net 验证器。
有什么建议吗?
【问题讨论】:
标签: c# asp.net image validation
这不能在客户端使用 javascript 来完成。也许你会发现一个用 flash、silverlight 或类似工具编写的文件上传组件,它允许按类型、大小和尺寸限制上传的文件。
【讨论】:
你根本无法知道客户端 JS 中的文件大小。
您可以做的是在请求到达服务器后检查文件大小,如果预期的文件大小超过某个限制,则取消传输:
在您的上传模块的 BeginRequest 中:
HttpWorkerRequest workerRequest = (HttpWorkerRequest)context.GetType().GetProperty("WorkerRequest", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(context, null);
// Indicates if the worker request has a body
if (workerRequest.HasEntityBody())
{
// Get the byte size of the form post.
long contentLength = long.Parse((workerRequest.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength)));
if (contentLength > MAX_UPLOAD_FILE_SIZE * 1024 )
{
workerRequest.CloseConnection();
context.Response.Redirect(SomeErrorPage);
}
}
尚未对此进行测试,但理论上它可能有效
编辑:没关系,我是个白痴。我以为他的意思是检查文件大小,而不是图像大小
【讨论】:
我找到了this Javascript snippet 并在我的系统上工作(IE 7.0.6001.18000)。您应该注意并检查可能的跨浏览器问题。
var tempImage;
function showDimensions() {
var imageName = document.forms[0].elements['myFile'].value;
if (imageName != '') {
imageName = 'file:///' + escape(imageName.split('\\').join('/'));
imageName = imageName.split('%3A').join(':');
tempImage = new Image();
tempImage.onload = getDimensions;
tempImage.src = imageName + '?randParam=' + new Date().getTime();
// append a timestamp to avoid caching issues - which happen if you
// overwrite any image with one of different dimensions, and try to
// get the dimensions again even with cache settings to max,
// in both ff and ie!
}
}
function getDimensions() {
alert(tempImage.width + ' x ' + tempImage.height);
}
【讨论】: