Javascript多文件上传实现代码(本地显示上传)

发布时间:2020-01-24编辑:脚本学堂
本文介绍了javascript 多文件上传的实例代码,实现文件上传时先在本地显示,感兴趣的朋友参考下。

1,选择图片后直接显示图片
 

复制代码 代码示例:
<input type="file" name="f1" accept="image/jpeg" onchange="document.preview.src=this.value;">
<img src="/images/spacer.gif" name="preview" width="300" border="0">

2,javascript上传多个图片。
 

复制代码 代码示例:
<input type="file" id="files" name="files[]" multiple /> 
<output id="list"></output> 
<script> 
  function handleFileSelect(evt) { 
    var files = evt.target.files; // FileList object 
 
    // files is a FileList of File objects. List some properties. 
    var output = []; 
    for (var i = 0, f; f = files[i]; i++) { 
      output.push('<li><strong>', f.name, '</strong> (', f.type || 'n/a', ') - ', 
                  f.size, ' bytes, last modified: ', 
                  f.lastModifiedDate.toLocaleDateString(), '</li>'); 
    } 
    document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>'; 
  } 
 
  document.getElementById('files').addEventListener('change', handleFileSelect, false); 
</script> 

3,拖拽的实现多个文件上传
 

复制代码 代码示例:
<div id="drop_zone">Drop files here</div> 
<output id="list"></output> 
 
<script> 
  function handleFileSelect(evt) { 
    evt.stopPropagation(); 
    evt.preventDefault(); 
 
    var files = evt.dataTransfer.files; // FileList object. 
 
    // files is a FileList of File objects. List some properties. 
    var output = []; 
    for (var i = 0, f; f = files[i]; i++) { 
      output.push('<li><strong>', f.name, '</strong> (', f.type || 'n/a', ') - ', 
                  f.size, ' bytes, last modified: ', 
                  f.lastModifiedDate.toLocaleDateString(), '</li>'); 
    } 
    document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>'; 
  } 
 
  function handleDragOver(evt) { 
    evt.stopPropagation(); 
    evt.preventDefault(); 
  } 
 
  // Setup the dnd listeners. 
  var dropZone = document.getElementById('drop_zone'); 
  dropZone.addEventListener('dragover', handleDragOver, false); 
  dropZone.addEventListener('drop', handleFileSelect, false); 
</script>