<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>利用Blob对象创建文件</title>
</head>

<body>
    <textarea name="" id="downloadFileTextarea" cols="30" rows="10"></textarea>
    <br>
    <button id="downloadFileButton">downloadFileButton</button>
    <script>
    function downloadFile(fileName, content, blobOptions) {

        // blobOptions = {
        //     type: 'text/csv',
        //     endings: 'native' // or transparent
        // };
        blobOptions = blobOptions || {};

        var blob = new Blob([content], blobOptions);
        var a = document.createElement('a');
        a.innerHTML = fileName;

        // 指定生成的文件名
        a.download = fileName;
        a.href = URL.createObjectURL(blob);

        document.body.appendChild(a);

        var evt = document.createEvent("MouseEvents");
        evt.initEvent("click", false, false);

        a.dispatchEvent(evt);

        document.body.removeChild(a);
    }

    downloadFileButton.onclick = function() {
        downloadFile('downloadFile.txt', downloadFileTextarea.value);
    };
    </script>
</body>

</html>

来源:https://blog.csdn.net/butterfly5211314/java/article/details/60757013

作者 铁血 汉子 2020年5月29日
2024/12/03/05:05:57pm 2020/5/29/17:36:21
0 3488