Как проверить расширение файла при перетаскивании

#javascript #html

#javascript #HTML

Вопрос:

Я создал загружаемый файл, который может принимать несколько файлов, но моя текущая проблема заключается в том, что когда пользователь перетаскивает несколько файлов, он принимает другой файл типа doc, кроме файла изображения.Вот мой код для этого:

  <div class="row">
       <div class="col-lg-12">
           <label class="fieldlabels">Photos:</label> 
              <!--input type="file" name="pic" accept="image/*"-->
                                        
            <input type="file" class="form-control" id="file_name2"  onchange="return fileValidation2()" name="file_name2" value="" title="Photos" accept="image/*" multiple="true"/>        
                                        <table class="table table-striped table-bordered" style="width:100%;" id="add_files2">
                       <thead>
                           <tr>
                  <th style="color:blue; text-align:center;">File Name</th>
                  <th style="color:blue; text-align:center;">Status</th>
                  <th style="color:blue; text-align:center;">File Size</th>
                  <th style="color:blue; text-align:center;">Type</th>
                  <th style="color:blue; text-align:center;">Action</th>
               </tr>
        </thead>
      <tbody>
 </tbody>
/table>
</div>
</div>
 

Вот мой сценарий, который я сделал до сих пор:

 function fileValidation2(){
    var fileInput = document.getElementById('file_name2');
    var filePath = fileInput.value;
    var allowedExtensions = /(.jpg|.jpeg|.png|.tiff|.tif)$/i;
    if(!allowedExtensions.exec(filePath)){
        alert('Please upload file having extensions .jpeg/.jpg/.png/.tiff/.tif/.xlsx/.pdf/.xls/.docx/.doc/.bump only.');
        fileInput.value = '';
        return false;
    }else{
        //Image preview
        if (fileInput.files amp;amp; fileInput.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('imagePreview').innerHTML = '<img src="' e.target.result '"/>';
            };
            reader.readAsDataURL(fileInput.files[0]);
        }
    }
}
 

Он отлично работает, когда пользователь нажимает выбрать файл во входном файле, но когда пользователь перетаскивает несколько файлов, содержащих файлы, кроме изображения, оно не включается.Кто-нибудь знает, как это сделать? Заранее спасибо.

https://i.stack.imgur.com/9iIbb.png

Zip-файл и другие файлы по-прежнему включаются, когда пользователь перетаскивает несколько файлов.

Комментарии:

1. вы можете сделать хотя бы «дешевую версию» и снова выполнить цикл, который вы использовали раньше if(!allowedExtensions.exec(fileInput.files[0].name)){ return; }

2. можете ли вы показать мне, как это работает? Спасибо

Ответ №1:

Ну, вам нужно переопределить события dragover , и drop у этих событий есть dataTransfer.files поле, которое является тем же интерфейсом, что и файловый ввод files , a FileList .

 const tbl = document.getElementById('file-table')

function formatSize(n){
  for(const unit of ['B', 'kB', 'MB', 'GB', 'TB']){
    if(n > 1024){
      n /= 1024;
    }else{
      if(n < 10){
        return n.toFixed(2)   unit
      }else{
        return n.toFixed(0)   unit;
      }
    }
  }
}


function fileValidation2(files){
    // Get file input from event target
    
    
    var allowedExtensions = /(.jpg|.jpeg|.png|.tiff|.tif)$/i;
    
    for(const file of files){
      if(!allowedExtensions.exec(file.name)){
          alert('Please upload file having extensions .jpeg/.jpg/.png/.tiff/.tif/.xlsx/.pdf/.xls/.docx/.doc/.bump only.');
          fileInput.value = '';
          return false;
      }else{
          //Image preview
          if (file) {
              var reader = new FileReader();
              reader.onload = function(e) {
                  // add one row to the file table
                  const row = tbl.insertRow()
                  // Create preview element
                  const img = document.createElement('img')
                  img.src = e.target.result;
                  img.classList.add('preview') // style 
                  row.insertCell().appendChild(img);
                  
                  row.insertCell().innerText = file.name;
                  // you decide what goes here
                  row.insertCell().innerText = 'pending';
                  // file.size has size in bytes, make it human readable
                  row.insertCell().innerText = formatSize(file.size)
                  // Trick to get file extension take the last item of the
                  // array obtained from the string splitted by dots.
                  row.insertCell().innerText = file.name.split('.').pop()
                  
                  // you decide what goes here
                  row.insertCell().innerText = '??'
              };
              reader.readAsDataURL(file);
          }
      }
    }
}

const row = tbl.insertRow();
const cell = row.insertCell()

document.getElementById('file_name2')
  .addEventListener('change', (e) => fileValidation2(e.target.files))

document.body.addEventListener('dragover', (e) => {
  e.preventDefault()
  e.stopPropagation()
  if(e.dataTransfer.files){
    // here you can get information from the files
    // even before dropping them
    document.body.classList.add('files')
  }
})

document.body.addEventListener('dragleave', (e) => {
  e.preventDefault()
  e.stopPropagation()
  document.body.classList.remove('files');
})

document.body.addEventListener('drop', (e) => {
  if(e.dataTransfer.files){
    e.preventDefault();
    e.stopPropagation()   
    fileValidation2(e.dataTransfer.files);
    document.body.classList.remove('files')
  }
}) 
 #file-table th {
  color: blue;
  text-align: center;
}

img.preview {
  max-width: 4e;
  max-height: 4em;
}

body.files {
  background-color: #e0e0ff;
  border: 3mm solid black;
} 
 <div class="row">
       <div class="col-lg-12">
           <label class="fieldlabels">Photos:</label> 
              <!--input type="file" name="pic" accept="image/*"-->
                                        
            <input type="file" class="form-control" id="file_name2" name="file_name2" value="" title="Photos" accept="image/*" multiple="true"/>          <table class="table table-striped table-bordered" style="width:100%;" id="file-table">
                       <thead>
                           <tr>
                  <th>Preview</th>
                  <th>File Name</th>
                  <th>Status</th>
                  <th>File Size</th>
                  <th>Type</th>
                  <th>Action</th>
               </tr>
        </thead>
      <tbody>
 </tbody>
</table>
</div>
</div>