【问题标题】:How to validate image size, height, width and format before upload with jquery of PHP? [duplicate]如何在使用 PHP 的 jquery 上传之前验证图像大小、高度、宽度和格式? [复制]
【发布时间】:2017-12-11 17:15:04
【问题描述】:

我想在使用 jquery 或 PHP 上传之前验证我的图像大小、高度、宽度和图像格式。我找到了很多答案,但我还没有发现所有的验证都在一起。

图片格式 = png,图片大小 = 2mb,图片高度 = 800px,图片宽度 = 600

【问题讨论】:

标签: javascript php jquery html wordpress


【解决方案1】:

由于您要求使用 jquery 或 PHP,我建议您使用 php 进行此类验证,出于安全考虑,您必须在服务器端验证您上传的文件。 首先检查文件是否为图像,您可以使用

mime_content_type or finfo_open()

验证您的文件是图像后,您可以选择宽度和高度

list($width, $height) = getimagesize($_FILES["fileToUpload"]); 

你使用的尺寸

$_FILES["fileToUpload"]["size"]

希望结合起来可以解决您的问题。

【讨论】:

    【解决方案2】:

    您可以使用 jQuery 来实现。

    演示代码 一旦写了一个普通的代码输入类型="file" 并在下面的jQuery中写下他们的id。

    $(document).ready(function(){
    
     var _URL = window.URL || window.webkitURL;
    
     $('#file').change(function () {
      var file = $(this)[0].files[0];
    
      img = new Image();
      var imgwidth = 0;
      var imgheight = 0;
      var maxwidth = 640;
      var maxheight = 640;
    
      img.src = _URL.createObjectURL(file);
      img.onload = function() {
       imgwidth = this.width;
       imgheight = this.height;
    
       $("#width").text(imgwidth);
       $("#height").text(imgheight);
       if(imgwidth <= maxwidth && imgheight <= maxheight){
    
        var formData = new FormData();
        formData.append('fileToUpload', $('#file')[0].files[0]);
    
        $.ajax({
          url: 'upload_image.php',
          type: 'POST',
          data: formData,
          processData: false,
          contentType: false,
          dataType: 'json',
          success: function (response) {
            if(response.status == 1){
              $("#prev_img").attr("src","upload/"+response.returnText);
              $("#prev_img").show();
              $("#response").text("Upload successfully");
            }else{
              $("#response").text(response.returnText);
            } 
          }
       });
      }else{
       $("#response").text("Image size must be "+maxwidth+"X"+maxheight);
      }
     };
     img.onerror = function() {
    
      $("#response").text("not a valid file: " + file.type);
     }
    
     });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-14
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 2014-12-13
      • 2016-05-08
      相关资源
      最近更新 更多