JavaScript 文件下载解决方案-download.js

太叔鸿
2023-12-01

官方网站:http://danml.com/download.html

下载地址:http://danml.com/js/download2.js

环境测试

手机QQ: 通过

华为手机浏览器:通过

小米手机浏览器:通过

Chrome(含移动端):通过

Firefox(含移动端):通过

Edge:通过

微信:未通过,待确认

简单使用

download(data, strFileName, strMimeType);
  • data: 要下载的数据,可以是 Blob、文件、字符串、URL
  • strFileName: 下载时指定文件名称
  • strMimeType:文件的MIME类型,可选。有利于向用户提供友好的信息

下载文字

download("我是文字", "text.txt", "text/plain");

下载html

download("data:text/plain,hello%20world", "dlDataUrlText.txt", "text/plain");

下载data:二进制数据

download("data:image/gif;base64,R0lGODlhRgAVAIcAAOfn5+/v7/f39yH5BAAAAP8ALAAAAABGABUAAAj/AAEIHAgggMGDCAkSRMgwgEKBDRM+LBjRoEKDAjJq1GhxIMaNGzt6DAAypMORJTmeLKhxgMuXKiGSzPgSZsaVMwXUdBmTYsudKjHuBCoAIc2hMBnqRMqz6MGjTJ0KZcrz5EyqA276xJrVKlSkWqdGLQpxKVWyW8+iJcl1LVu1XttafTs2Lla3ZqNavAo37dm9X4eGFQtWKt+6T+8aDkxUqWKjeQUvfvw0MtHJcCtTJiwZsmLMiD9uplvY82jLNW9qzsy58WrWpDu/Lp0YNmPXrVMvRm3T6GneSX3bBt5VeOjDemfLFv1XOW7kncvKdZi7t/S7e2M3LkscLcvH3LF7HwSuVeZtjuPPe2d+GefPrD1RpnS6MGdJkebn4/+oMSAAOw==", "dlDataUrlBin.gif", "image/gif");

下载ajax接口返回的数据

var x=new XMLHttpRequest();
    x.open("GET", "http://danml.com/wave2.gif", true);
    x.responseType = 'blob';
    x.onload=function(e){download(x.response, "dlBinAjax.gif", "image/gif" ); }
    x.send();

完整测试代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://danml.com/js/download2.js"></script>
</head>
<body>
    <button onclick="downloadText()">下载文字</button><br>
    <button onclick="downloadHtml()">下载HTML</button><br>
    <button onclick="downloadBinary()">下载data:二进制数据</button><br>
    <button onclick="downloadFromAjax()">从ajax接口下载</button><br>
</body>
<script>
    function downloadText() {
        download("data:text/plain,hello%20world", "dlDataUrlText.txt", "text/plain");
    }

    function downloadHtml() {
        download(document.body.outerHTML, "dlHTML.html", "text/html");
    }

    function downloadBinary() {
        download("data:image/gif;base64,R0lGODlhRgAVAIcAAOfn5+/v7/f39yH5BAAAAP8ALAAAAABGABUAAAj/AAEIHAgggMGDCAkSRMgwgEKBDRM+LBjRoEKDAjJq1GhxIMaNGzt6DAAypMORJTmeLKhxgMuXKiGSzPgSZsaVMwXUdBmTYsudKjHuBCoAIc2hMBnqRMqz6MGjTJ0KZcrz5EyqA276xJrVKlSkWqdGLQpxKVWyW8+iJcl1LVu1XttafTs2Lla3ZqNavAo37dm9X4eGFQtWKt+6T+8aDkxUqWKjeQUvfvw0MtHJcCtTJiwZsmLMiD9uplvY82jLNW9qzsy58WrWpDu/Lp0YNmPXrVMvRm3T6GneSX3bBt5VeOjDemfLFv1XOW7kncvKdZi7t/S7e2M3LkscLcvH3LF7HwSuVeZtjuPPe2d+GefPrD1RpnS6MGdJkebn4/+oMSAAOw==", "dlDataUrlBin.gif", "image/gif");
    }

    function downloadFromAjax() {
        var x=new XMLHttpRequest();
        x.open("GET", "http://39.107.120.250/tt.jpg", true); // 注意跨域问题d
        x.responseType = 'blob';
        x.onload=function(e){
            download(x.response, "dlBinAjax.gif", "image/jpg" ); 
        }
        x.send();
    }

</script>
</html>
 类似资料: