如何使用 HTML5 和 JSZip 解压 ZIP 存档中的文件
在我们之前的文章如何使用 JSZip 在 HTML5/Javascript 中读取本地 ZIP中,我们提供了如何使用 JSZip 通过 HTML5 列出本地 ZIP 存档中文件的示例。
这篇文章将在此基础上扩展,以读取本地 ZIP 存档文件中压缩文件的内容。
在此示例中,我们将使用 HTML5 <input type="file"> 读取本地 ZIP 文件并解压其内容。我们将读取 word/document.xml 文件,因此你可以上传任何 .docx 文件来测试。
uncompress.js
JSZip.loadAsync(ev.target.result).then(function(zip) {
zip.file("word/document.xml").async("ArrayBuffer").then(function(data) {
// data 是一个 ArrayBuffer
// TODO 你的代码放在这里!
})
}).catch(function(err) {
console.error("Failed to open", filename, " as ZIP file:", err);
})完整示例
index.html
<html>
<body>
<input type="file" id="myfile" onchange="onMyfileChange(this)" />
<script src="https://unpkg.com/[email protected]/dist/jszip.js" type="text/javascript"></script>
<script type="text/javascript">
function onMyfileChange(fileInput) {
if(fileInput.files[0] == undefined) {
return ;
}
var filename = fileInput.files[0].name;
var reader = new FileReader();
reader.onload = function(ev) {
JSZip.loadAsync(ev.target.result).then(function(zip) {
zip.file("word/document.xml").async("ArrayBuffer").then(function(data) {
// data 是一个 ArrayBuffer
// TODO 你的代码放在这里!
})
}).catch(function(err) {
console.error("Failed to open", filename, " as ZIP file:", err);
})
};
reader.onerror = function(err) {
console.error("Failed to read file", err);
}
reader.readAsArrayBuffer(fileInput.files[0]);
}
</script>
</body>
</html>Check out similar posts by category:
HTML, Javascript
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow