把文本变成文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button onclick="exportCSVFile('文件内容AAA','文件名')">点击下载文件</button>
</body>
<script>
    function exportCSVFile(items, fileTitle) {//items:为文件的内容,fileTitle:为文件的名字
        var exportedFilenmae = fileTitle + '.log' || 'export.log';//文件后缀名
        var blob = new Blob([items]);
        if (navigator.msSaveBlob) { // IE 10+
            navigator.msSaveBlob(blob, exportedFilenmae);
        } else {
            var link = document.createElement("a");
            if (link.download !== undefined) { // feature detection
                // Browsers that support HTML5 download attribute
                var url = URL.createObjectURL(blob);
                link.setAttribute("href", url);
                link.setAttribute("download", exportedFilenmae);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            };
        };
    };
</script>
</html>

 

posted @ 2022-12-14 15:02  芬-mi  阅读(162)  评论(0编辑  收藏  举报