在javascript中检查ajax post事件之前的图像尺寸

时间:2017-09-29 14:42:35

标签: javascript ajax

我尝试从上传的图片中访问维度,然后将其发布到上传后的终结点。如果你看,有一个variable issueArrived应该确定图像是否太小,如果是这样,否定上传过程。 很遗憾,在上传到服务器之后,图像才会访问维度检查。任何帮助将不胜感激。

// internal function that creates an input element
var file = newElement("input", 0, "");

// sets the input element as type file
file.type = "file";
file.multiple = "multiple";
file.name = "photoupload[]";
file.accept = "image/*";

var issueArrived = false;
file.onchange = function(e) {
    // internal function that creates an image element
    var img = newElement("img", 0, "");
    img.onload = function(){
       var cw = img.width;
       var ch = img.height;
       if(cw < 500 || ch < 500) {
         alert("Photo must be atleast 500x500");
         issueArrived = true;
         return false;
       }           
   }
   img.src = URL.createObjectURL(this);
   if (issueArrived) return;
   var formdata = new FormData();
   formdata.append("photoupload[]", this);
   var x = new XMLHttpRequest();
   x.open("POST", "/media/uploadphotos", true);
   x.send(formdata);
}
file.click();

1 个答案:

答案 0 :(得分:0)

onchange方法是异步的。你不能期望将来自issueArrived的值设置为外部访问。

您可以这样重写:

file.onchange=function(e){
    // internal function that creates an image element
    var img=newElement("img",0,"");
    img.onload=function(){
       var cw=img.width;
       var ch=img.height;
       if(cw<500||ch<500){
         alert("Photo must be atleast 500x500");
       } else {
        var formdata=new FormData();
        formdata.append("photoupload[]",this);
        var x=new XMLHttpRequest();
        x.open("POST","/media/uploadphotos",true);
        x.send(formdata);
       } 
   }
   img.src=URL.createObjectURL(this);

}
file.click();

或者,更好的是,您可以创建一个获取文件并返回承诺的函数。

function checkSize(fileToCheck) {

  return new Promise( function(resolve, reject) {
    var img = newElement("img",0,"");
    img.onload=function(){
      var cw=img.width;
      var ch=img.height;
      cw<500||ch<500 ? reject() : resolve()
    }
    img.src=URL.createObjectURL(fileToCheck);
  })
}
...
file.onchange=function(e){
  checkSize(this)
  .then( function() { /* success handler */ } )
  .catch( function() { /* error handler */ } )
}