webkitdirectory 实现文件夹上传

文件夹上传这个功能在web端可能有需求,这里就简单介绍下用法。

目前只有谷歌浏览器还有Microsoft Edge支持按照文件夹进行上传,具体可以看下百度云盘的网页版的上传按钮,在火狐下就支持按照文件进行上传,而在谷歌和Edge下,就会给用户提供一个下拉,让用户选择是根据文件进行上传还是根据文件夹进行上传。

而在谷歌浏览器下,也不是没有条件的支持,必须在input上加入一个属性:webkitdirectory后才会予以支持。

加上后效果就是这样的

附上一个文件夹跟单个文件上传的例子

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
     <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</head>
<body>
    <input id="fileFolderMore"  type="file" name="file" webkitdirectory/>

    <input id="fileFolderOne" type='file' name="file">
</body>
<script>
  $('#fileFolderMore').change(function(e){
    // console.log(e)
    var files = e.target.files; 
    console.log(files)
  })
  $('#fileFolderOne').change(function(e){
    // console.log(e)
    var files = e.target.files;   
    console.log(files)
  })

</script>
</html>

 上面文件夹选择后会显示文件夹的路径的

上传的话可以用formData,也可以用form表单。

猜你喜欢

转载自www.cnblogs.com/wangmaoling/p/11066243.html