js檢測上傳檔案型別程式碼例項

antzone發表於2017-04-06

本章節分享一段程式碼例項,它實現了檢測上傳檔案型別的功能。

程式碼例項如下:

[JavaScript] 純文字檢視 複製程式碼
function Checkfiles(){
  var fup = document.getElementById('logo1');
  var fileName = fup.value;
  var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
  if(ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG" || ext == "png" || ext == "PNG"){
    return true;
  }else{
    alert("Upload JPG, JPEG, PNG, GIF images only");
    fup.focus();
    return false;
  }
}

上面的程式碼實現了檢測功能,下面簡單介紹一下它的實現過程。

一.程式碼註釋:

(1).function Checkfiles(){},此方法實現了判斷功能。

(2).var fup = document.getElementById('logo1'),這個是獲取上傳空間的元素物件,比如input file。

(3).var fileName = fup.value,獲取value屬性值,也就是檔案的路徑。

(4).var ext = fileName.substring(fileName.lastIndexOf('.') + 1),擷取檔案的字尾名稱。

(5).if(ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG" || ext == "png" || ext == "PNG"){

  return true;

},如果字尾名稱屬於以上幾個就返回true。

(6).else{

  alert("Upload JPG, JPEG, PNG, GIF images only");

  fup.focus();

  return false;

},否則的話給出提示,並且上傳元素獲取焦點,並跳出函式。

二.相關閱讀:

(1).substring()方法可以參閱javascript substring()一章節。

(2).lastIndexOf()方法可以參閱javascript lastIndexOf()一章節。

相關文章