【问题标题】:How to check file extension when drag and drop拖放时如何检查文件扩展名
【发布时间】:2021-02-18 08:59:45
【问题描述】:

我已经完成了一个可以接受多个文件的上传文件,但我目前的问题是当用户拖放多个文件时,它接受除图像文件之外的其他文档类型文件。这是我的代码:

 <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 && 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 文件和其他文件。

【问题讨论】:

  • 你至少可以做“便宜的版本”,然后在你的循环中再做一次,你以前用过的if(!allowedExtensions.exec(fileInput.files[0].name)){ return; }
  • 你能告诉我它是如何工作的吗?谢谢

标签: javascript html


【解决方案1】:

你必须覆盖事件dragoverdrop,这些事件有一个dataTransfer.files字段,它与文件输入files的接口相同,一个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>

【讨论】:

    猜你喜欢
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 2019-04-22
    相关资源
    最近更新 更多