可以实现js在浏览器中选择本地文件夹直接将其打包成zip压缩包,示例代码如下:
点击查看全文
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>选择文件夹打包成 Zip 文件</title> </head> <body> <input type="file" id="fileInput" multiple webkitdirectory mozdirectory /> <button id="packButton">打包成 Zip</button> <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/filesaver.js"></script> <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/jszip.js"></script> <script> document.getElementById('packButton').addEventListener('click', function() { var fileInput = document.getElementById('fileInput'); if (!fileInput.files.length) { alert('请选择文件或文件夹'); return; } var zip = new JSZip(); Array.from(fileInput.files).forEach(function(file) { // 由于无法直接获取文件夹结构,我们尝试通过文件的webkitRelativePath属性来推断 // 注意:这并不是一个完美的解决方案,因为它依赖于浏览器的实现 var path = file.webkitRelativePath || file.name; zip.file(path, file); }); zip.generateAsync({type:"blob"}).then(function(content) { saveAs(content, "packedFiles.zip"); }); }); </script> </body> </html>
网友回复