文件下载
JS代码: var eleTextarea = document.querySelector('textarea'); var eleButton = document.querySelector('input[type="button"]'); // 下载文件方法 var funDownload = function (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); }; if ('download' in document.createElement('a')) { // 作为test.html文件下载 eleButton.addEventListener('click', function () { funDownload(eleTextarea.value, 'test.html'); }); } else { eleButton.onclick = function () { alert('浏览器不支持'); }; }
三、借助Base64实现任意文件下载 var funDownload = function (domImg, filename) { // 创建隐藏的可下载链接 var eleLink = document.createElement('a'); eleLink.download = filename; eleLink.style.display = 'none'; // 图片转base64地址 var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); var width = domImg.natureWidth; var height = domImg.natureHeight; context.drawImage(domImg, 0, 0); // 如果是PNG图片,则context.toDataURL('image/png') eleLink.href = context.toDataURL('image/jpeg'); // 触发点击 document.body.appendChild(eleLink); eleLink.click(); // 然后移除 document.body.removeChild(eleLink); };
转自 张鑫旭大神 https://www.zhangxinxu.com/wordpress/2017/07/js-text-string-download-as-html-json-file/