2008-09-05 15 views
37

は私がユーザーがファイルをアップロードするファイルを選択したかどうかを確認するにはどうすればよいですか?

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

タグを持っており、ファイルがユーザによって選択された場合にはIE6(以上)には、私が決めるんどのように、ボタンを提出した場合。 FFで

、私はちょうど行います

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

しかし、それはIEでは動作しません。これはIEで動作

答えて

86

(および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);"/> 

に働くことを願っています変更時にこの関数を呼び出します。

関連する問題