js\jquery下载本地txt文档

有一个功能,是需要将相对位置下txt文件读取,并下载;相对路径:“../../assets/download/版本更新日志.txt”

利用a标签进行如下设置,结果只是预览内容,没有下载txt文档;

<a href="../../assets/download/版本更新日志.txt" download="版本更新日志" title="版本更新日志">版本更新日志.txt</a>

于是换了思路,通过以下功能进行txt文件下载:

var a=document.getElementById('a')
        a.addEventListener('click',()=>{
            let data='';
            download('版本更新日志.txt',data)
        })
        function download(filename,text){
            var pom = document.createElement("a");
            pom.setAttribute(
              "href",
              "data:text/plain;charset=utf-8," + encodeURIComponent(text)
            );
            pom.setAttribute("download", filename);
            if (document.createEvent) {
              var event = document.createEvent("MouseEvents");
              event.initEvent("click", true, true);
              pom.dispatchEvent(event);
            } else {
              pom.click();
            }
         
        }

通过ajax获取相对位置下的txt内容

            $.ajax({
                url: "../../assets/download/版本更新日志.txt",
                success: function(data, status) {
                    download('版本更新日志.txt',data)
                },
                error: function(data, status) {
                    console.log('log err',arguments)
                }
            });

完整的代码如下:

    var a=document.getElementById('a')
        a.addEventListener('click',()=>{
            $.ajax({
                url: "../../assets/download/版本更新日志.txt",
                success: function(data, status) {
                    download('版本更新日志.txt',data)
                },
                error: function(data, status) {
                    console.log('log err',arguments)
                }
            });

           
        })
        function download(filename,text){
            var pom = document.createElement("a");
            pom.setAttribute(
              "href",
              "data:text/plain;charset=utf-8," + encodeURIComponent(text)
            );
            pom.setAttribute("download", filename);
            if (document.createEvent) {
              var event = document.createEvent("MouseEvents");
              event.initEvent("click", true, true);
              pom.dispatchEvent(event);
            } else {
              pom.click();
            }
         
        }
posted @ 2022-05-11 13:32  浪潮行舟  阅读(800)  评论(0编辑  收藏  举报