通常我们知道一个文件的url,在前端我们可以通过代码:

window.open(url)

实现下载文件的功能,但是如何是图片url的话,会新开一个页面,并不会将图片下载,那怎么实现将图片下载下来呢?

1.方法一

<a>标签.html5的a标签增加了download属性,可利用此属性实现图片下载。

<a href="https://www.jitailed.com/logo.png" download="logo.png">下载图片</a>

• 将a标签的href属性指向图片的地址;同时增加download属性;即可实现点击下载.

• download属性的属性值选填,代表下载图片的名称,如不填写,则使用href中的图片名称,即图片的原名称.

• a标签的download属性目前主流浏览器只有火狐和谷歌支持.

因为上诉方法只有火狐和谷歌支持,所以我们还要兼容其它浏览器

2.方法二

<iframe>标签.生成iframe,src指向图片地址,调用document.execCommand(“SaveAs”)方法.

所以在Trident内核浏览器(IE等)下,给按钮(a标签)绑定事件,使用创建标签方法;

在火狐,谷歌下使用<a>标签的download属性进行下载.

首先判断浏览器,决定增加属性,还是绑定事件;

在绑定事件的逻辑内,

首先判断页面是否存在指定的<iframe>,不存在则生成,存在则修改src属性.

然后调用SaveAs命令进行保存.

下面举个简单的栗子.在图片列表中,给每个图片增加一个下载功能按钮.

① html代码

<div class="card">

    <img id="testimg" src="beauty.jpg"/>

    <a href="javascript:;" class="down_btn_a">点击下载</a>

</div>

<div class="card">

    <img id="testimg" src="timg.jpg"/>

    <a href="javascript:;" class="down_btn_a">点击下载</a>

</div>

② css代码

*{ padding: 0; margin: 0;}

img { display: block; width: 500px;}

.card{ display: inline-block; position: relative; width: 400px; height: 250px;}

.card img{ width: 100%;}

.card .down_btn_a { display: inline-block; position: absolute; right: 0; bottom: 0; width: 100px; height: 40px; line-height: 40px; background-color: #20b1aa; text-decoration: none; text-align: center; color: #fff;}

.card .down_btn_a:hover { background-color: #ccc; color: #000;}

③ js功能实现代码

//判断是否为Trident内核浏览器(IE等)函数

function browserIsIe() {

    if (!!window.ActiveXObject || "ActiveXObject" in window){

        return true;

    }

    else{

        return false;

    }

}

//创建iframe并赋值的函数,传入参数为图片的src属性值.

function createIframe(imgSrc) {

    //如果隐藏的iframe不存在则创建

    if ($("#IframeReportImg").length === 0){

        $('<iframe style="display:none;" id="IframeReportImg" name="IframeReportImg" οnlοad="downloadImg();" width="0" height="0" src="about:blank"></iframe>').appendTo("body");

    }

    //iframe的src属性如不指向图片地址,则手动修改,加载图片

    if ($('#IframeReportImg').attr("src") != imgSrc) {

        $('#IframeReportImg').attr("src",imgSrc);

    } else {

        //如指向图片地址,直接调用下载方法

        downloadImg();

    }

}

//下载图片的函数

function downloadImg() {

    //iframe的src属性不为空,调用execCommand(),保存图片

    if ($('#IframeReportImg').src != "about:blank") {

        window.frames["IframeReportImg"].document.execCommand("SaveAs");

    }

}

//接下来进行事件绑定

var aBtn = $(".card .down_btn_a");

if (browserIsIe()) {

    //是ie等,绑定事件

    aBtn.on("click", function() {

        var imgSrc = $(this).siblings("img").attr("src");

        //调用创建iframe的函数

        createIframe(imgSrc);

    });

} else {

    aBtn.each(function(i,v){

    //支持download,添加属性.

    var imgSrc = $(v).siblings("img").attr("src");

    $(v).attr("download",imgSrc);

    $(v).attr("href",imgSrc);

    })

}