如何在上传之前使用 PHP 的 jquery 验证图像的大小、高度、宽度和格式?

jam*_*mes 2 html javascript php wordpress jquery

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

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

小智 6

您可以使用 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);
 }

 });
});
Run Code Online (Sandbox Code Playgroud)