【问题标题】:ASP.NET: Validate file size (width and height) before uploadASP.NET:上传前验证文件大小(宽度和高度)
【发布时间】:2009-10-16 10:52:12
【问题描述】:

有没有办法在上传到服务器之前验证图像大小(高度和宽度)?

我认为正在使用 Javascript,但我不知道如何。或者也许使用一些客户端 asp.net 验证器。

有什么建议吗?

【问题讨论】:

    标签: c# asp.net image validation


    【解决方案1】:

    这不能在客户端使用 javascript 来完成。也许你会发现一个用 flash、silverlight 或类似工具编写的文件上传组件,它允许按类型、大小和尺寸限制上传的文件。

    【讨论】:

      【解决方案2】:

      你根本无法知道客户端 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);
                        }
              }
      

      尚未对此进行测试,但理论上它可能有效

      编辑:没关系,我是个白痴。我以为他的意思是检查文件大小,而不是图像大小

      【讨论】:

        【解决方案3】:

        我找到了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);
        }
        

        【讨论】:

        • 我不会为一大堆安全问题工作。同样在 IE7+ 中,Upload File 元素的值将不再包含整个路径。仅包含文件名。
        • +1:我只是在此处使用 IE7 运行此代码并运行;无论如何,很高兴被警告这个可能的问题,ty
        • 奇怪的是,您可以在 IE7 中获得完整的文件路径。我清楚地记得由于这种行为变化而不得不重写我们的上传组件......也许未来的一些 IE7 更新会恢复到旧的方式
        猜你喜欢
        • 1970-01-01
        • 2012-09-16
        • 2021-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-11
        • 2013-11-18
        相关资源
        最近更新 更多