2017-05-12 48 views
0

我已經包含上傳文件的列表:如何比較上傳文件的寬度和高度?

let files = [File, File, File...]; 

和另一上傳文件進行比較:

let file = ...; 

我要檢查的file存在於列表或不(通過比較name/width/height/size/type) ;

這裏是我的方法:

let f = files.find(function (x) { 
    return x.name === file.name && x.type === file.type && 
      x.width === file.width && x.height === file.height && 
      x.size === file.size; 
}); 

if (f) { 
    // exist 
} 

x.widthx.heightfile.widthfile.height總是返回undefined

undefined 總是等於undefined(當然=))),但這不是我的意思,我想要得到真正的價值。

感謝this answer,我編輯了一些地方,但尚未完成。

let f = files.find(function (x) { 
    let x_img = new Image(); 
    x_img.onload = function() { 

     let file_img = new Image(); 
     file_img.onload = function() { 

      // we can compare x_img width/height and file_img width/height here 
      // but these functions look like the callback function 
      // so we can't delay to get width and height 

     }; 
     file_img.src = window.URL.createObjectURL(file); 

    }; 
    x_img.src = window.URL.createObjectURL(x); 

    // the main predicate here 
    return x.name === file.name && x.size === file.size && x.type === file.size &&... 

    // and how to compare width and height? 
}); 

你能幫我完成代碼嗎?謝謝!

+0

根據您的要求比較'name','size'和'lastModified'應該足以檢測,如果用戶選擇了相同文件兩次。 – Prinzhorn

+0

@Prinzhorn謝謝,這也意味着:在這種情況下,我無法獲取和比較'width/height'? – Vayne

回答

1

得到naturalWidthnaturalHeight如下

var x = { 
 
    name: "crayola-rango.jpg", 
 
    type: "image/jpeg", 
 
    width: 896, 
 
    height: 259, 
 
    size: 37596 
 
}; //file to compare 
 
function find(x, files, callback) { 
 
    var len = files.length, 
 
    i, 
 
    _find = false, 
 
    fun = function (file, callback) { 
 
     var img = new Image(); 
 
     img.onload = function() { 
 
     // no longer need to read the blob so it's revoked 
 
     window.URL.revokeObjectURL(file); 
 
     var width = img.naturalWidth, 
 
      height = img.naturalHeight; 
 
     if (x.name === file.name && x.type === file.type && x.width === width && x.height === height && x.size == file.size) { 
 
      callback(file); 
 
      _find = true; 
 
     } 
 
     } 
 
     img.src = window.URL.createObjectURL(file); 
 
    }; 
 
    for (var i = 0; i < len; i += 1) { 
 
    if (_find) { 
 
     break; 
 
    } 
 
    fun(files[i], callback); 
 
    } 
 
} 
 
//only test 
 
var file = document.getElementById("files"); 
 
file.addEventListener("change", function() { 
 
    //call this 
 
    find(x, file.files, function (file) { 
 
    console.log(file); 
 
    }); 
 
});
<input id="files" type="file" multiple>

+0

謝謝,但我不能把主謂詞放在'onload'函數中。這是行不通的:'img.onload = function(){return x.name === file.name && img.naturalWidth === file.naturalWidth ...}' – Vayne

+0

@foo參見update – AvrilAlejandro

相關問題