2008-09-05 122 views
37

如果我有一個如何確定用戶是否選擇文件上傳文件?

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

標籤,如果一個文件被用戶選擇的提交按鈕,我怎麼決定,在IE6(及以上)。

在FF,我只是做:

var selected = document.getElementById("uploadBox").files.length > 0; 

但是,這並不在IE瀏覽器。

回答

86

這在IE(和FF,我相信):

if(document.getElementById("uploadBox").value != "") { 
    // you have a file 
} 
5

這段代碼在我的本地環境中工作,希望它也將工作在現場

var nme = document.getElementById("uploadFile"); 
if(nme.value.length < 4) { 
    alert('Must Select any of your photo for upload!'); 
    nme.focus(); 
    return false; 
} 
0
function validateAndUpload(input){ 
    var URL = window.URL || window.webkitURL; 
    var file = input.files[0]; 

    if (file) { 
     var image = new Image(); 

     image.onload = function() { 
      if (this.width) { 
       console.log('Image has width, I think it is real image'); 
       //TODO: upload to backend 
      } 
     }; 

     image.src = URL.createObjectURL(file); 
    } 
};​ 

<input type="file" name="uploadPicture" accept="image/*" onChange="validateAndUpload(this);"/> 

在更改時調用此函數。

相關問題