前端实现对ZIP 压缩文件解压,实现前端直接展示结果,比如图片,压缩包等 audio对象进行播放
程序员文章站
2022-03-09 19:17:09
...
其中后台代码,很简单:
/// <summary>
/// 获取压缩的zip文件
/// </summary>
/// <returns></returns>
public ActionResult ZipFile()
{
string b = "host.zip";
string c = "1.zip";
byte[] data = System.IO.File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, c));
return File(data, "application/zip");
}
前端需要用到的Lib
https://www.bootcdn.cn/jszip/
https://www.bootcdn.cn/FileSaver.js/
整体效果代码
<body>
<audio id="MP3Play" controls></audio>
<input id="Play" οnclick="Play()" value="播放" type="button" />
</body>
</html>
<script src="~/Scripts/jquery-3.3.1.js"></script>
<script src="~/JS/jszip.js"></script>
<script src="~/JS/FileSaver.js"></script>
<script type="text/javascript">
$(function () {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/home/ZipFile", true);
xmlhttp.responseType = "blob";
xmlhttp.onload = function () {
console.log(this);
if (this.status == 200) {
var blob = this.response;
var new_zip = new JSZip();
new_zip.loadAsync(blob)
.then(function (file) {
var files = file.files;
for (var f in files) {
var zipobj = files[f];
if (!zipobj.dir) {
new_zip.file(f).async("blob")
.then(function (blob) {
//获取blob对象地址,并把值赋给容器
var mp3url = URL.createObjectURL(blob);
$("#MP3Play").attr("src", mp3url);
//setTimeout("revokeUrl('" + mp3url + "')", "2000");
});
}
}
});
}
}
xmlhttp.send();
});
</script>
<script type="text/javascript">
function Play() {
var play = document.getElementById("MP3Play");
play.play();
}
function revokeUrl(url) {
window.URL.revokeObjectURL(url);
console.log("开始准备播放");
}
</script>
实现了对压缩文件的解压,以及Audio赋值,进行播放,测试过,结果正常。
下一篇: Collections集合工具类