【问题标题】:How do I restrict image uploads to a certain height and width?如何将图像上传限制在一定的高度和宽度?
【发布时间】:2020-04-09 13:43:56
【问题描述】:
function filePreview (input) {
    if(input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function(e) {
        $('#uploadForm + img').remove();
        $('#uploadForm').after('<img src="'+e.target.result+'" width="840" height="600" />');
      }
      reader.readAsDataURL(input.files[0]);
      }
  }

    $('#fileThumbnail').change(function() {
      filePreview(this);
    });

我正在尝试预览图像,但仅接受宽度:840 像素,高度:600 像素的图像,不多也不少。并返回错误以选择具有这些精确尺寸的图像

【问题讨论】:

  • 您可以在服务器端查看图片大小,请尝试使用ajax上传器,并在满足您的分辨率要求的情况下将图片保存到特定目录。
  • @RahulSawant 如果我们使用客户端解决方案,我们不能完全信任所有浏览器,在某种程度上 javascript 解决方案很有用,但最终用户可以使用任何类型的浏览器。所以我认为服务器端检查将是一个理想的解决方案

标签: jquery html image file-upload


【解决方案1】:

您可以尝试将文件转换为Image元素,以便在应用之前获取宽度和高度。

我还添加了这一行 /(image\/)(jpeg|jpg|bmp|gif)/.test(input.files[0].type) 以在转换前检查文件扩展名(仅接受扩展名为 jpefjpgbmpgif 的图像)

function filePreview (input) {
        if(input.files && input.files[0] && /(image\/)(jpeg|jpg|bmp|gif)/.test(input.files[0].type)) {
        
          var reader = new FileReader();
          reader.onload = function(e) {
              
              var image = new Image();
              
              image.onload = function () {
                // you can check the image width and height here
                var width = this.width;
                var height = this.height;
                
                if (width === 840 && height === 600) {
                  // code goes here...

                  // $('#uploadForm + img').remove();
                  // $('#uploadForm').after(this);
                }
                
                $('body').append(this);
              };
              
              image.src = this.result;
              
          }
          
          reader.readAsDataURL(input.files[0]);
        }
    }
    
        $('#fileThumbnail').change(function() {
          filePreview(this);
        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<input type="file" id="fileThumbnail" />

【讨论】:

  • 我不再预览图像了
  • @LexSha 您可以使用if 块内的代码开始上传:if (width === 840 &amp;&amp; height === 600) { ... }。无法上传其他不具有此尺寸的图片。
  • @LexSha 不。您可以再次检查我的代码。我已将 &lt;img src="'+e.target.result+'" width="840" height="600" /&gt; 替换为 this
  • @LexSha $('#uploadForm').after(this) 就够了。
  • @LexSha 您是否尝试过像我上面提到的那样将文件转换为Image 元素? var image = new Image(); image.onload..... image.src....都在reader.onload函数里面
猜你喜欢
  • 2012-03-11
  • 2017-10-31
  • 1970-01-01
  • 2014-12-13
  • 1970-01-01
  • 2019-12-25
  • 2016-07-10
  • 1970-01-01
  • 2022-08-19
相关资源
最近更新 更多