前端實現對ZIP 壓縮文件解壓,實現前端直接展示結果,比如圖片,壓縮包等 audio對象進行播放

其中後臺代碼,很簡單:

        /// <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賦值,進行播放,測試過,結果正常。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章