前端js 实现文件下载

https://www.zhangxinxu.com/wordpress/2017/07/js-text-string-download-as-html-json-file/ 侵删

 

1.H5 download属性

function downFile(content, filename) {
    // 创建隐藏的可下载链接
    var eleLink = document.createElement('a');
    eleLink.download = filename;
    eleLink.style.display = 'none';
    // 字符内容转变成blob地址
    var blob = new Blob([content]);
    eleLink.href = URL.createObjectURL(blob);
    // 触发点击
    document.body.appendChild(eleLink);
    eleLink.click();
    // 然后移除
    document.body.removeChild(eleLink);
};

downFile(下载地址, 保存名称);

 

2.iframe方式

// if (typeof(download.iframe) == 'undefined') {
            //     var iframe = document.createElement('iframe');
            //     download.iframe = iframe;
            //     document.body.appendChild(download.iframe);
            // };
            // download.iframe.src = newdownloadUrl;
            // download.iframe.style.display = "none";

3.form方式

// var $eleForm = $("<form method='get'></form>");
            // $eleForm.attr("action", "https://codeload.github.com/douban/douban-client/legacy.zip/master");
            // $eleForm.attr("action", url);
            // $(document.body).append($eleForm);
            // $eleForm.submit();

 

posted @ 2018-07-13 16:12  abcByme  阅读(20626)  评论(4编辑  收藏  举报