Iframe和a標籤的downLoad新屬性實現-呼叫瀏覽器的本地下載功能
阿新 • • 發佈:2019-02-10
//js中的html結構
<a class="downLoadA" style="display: inline-block;float:left;width: 40px;height: 40px;"><img id="downLoadImg" style="width:40px;height:40px;border:none;" type="button" class="downLoadImg_btn" src="/ngcs/src/js/communication/huawei/media/clientArea/downLoadImg.png"/></a</div>
//js如下完整程式碼;
//點選呼叫瀏覽器的本地下載功能
var downLoadImg = function() {//獲取圖片的路徑
var imgPathSrc = $('#headImg',this.$el).attr("src");
if(imgPathSrc.indexOf("_min") != "-1") {
var temp = imgPath.indexOf("_min").split("_min");
var part1 = temp[0];
var part2 = temp[1];
imgPathSrc = part1 + part2;
}
function myBrowser() {
var userAgent = navigator.userAgent; //取得瀏覽器的userAgent字串
var isOpera = userAgent.indexOf("Opera") > -1;
//判斷是否IE瀏覽器
if(userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1) {
return "IE";
};
//判斷是否IE瀏覽器
if(userAgent.indexOf("Trident") > -1) {
return "Edge";
}
}
//呼叫當前時間作為圖片的名字
function getNowFormatDate() {
var date = new Date();
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = date.getFullYear() + month + strDate + date.getHours()+ date.getMinutes()+ date.getSeconds()+randNum(0, 9)+randNum(0, 9)+randNum(0, 9)+randNum(0, 9);
return currentdate;
}
function randNum(x, y) {
return Math.floor(Math.random()*(y - x + 1) + x);
}
//彈框的點選事件呼叫本地下載功能
//如果隱藏IFRAME不存在,則新增
if (!document.getElementById("IframeReportImg")){
iframeIEDown = $('<iframe style="display:none;" id="IframeReportImg" src='+imgPathURL+' name="IframeReportImg" width="0" height="0" src="about:blank"></iframe>');
iframeIEDown.appendTo("body");
}
if(navigator.userAgent.toLowerCase().indexOf('se 2.x')>-1&&navigator.userAgent.toLowerCase().indexOf('trident')){
setTimeout(function(){
document.frames["IframeReportImg"].document.execCommand("SaveAs");
$('#IframeReportImg').remove();
},90);
}else{
setTimeout(function(){
document.frames["IframeReportImg"].document.execCommand("SaveAs");
$('#IframeReportImg').remove();
},30);
}
}
if(myBrowser() === "IE" || myBrowser() === "Edge") {
DownLoadReportIMG(imgPathSrc)
} else {
//!IE
$('.downLoadA').attr('href', imgPathSrc);
if(navigator.userAgent.indexOf("Firefox") > -1){
$('.downLoadA').attr('download', getNowFormatDate()+imgPathSrc.substr(-4));
}else{
$('.downLoadA').attr('download', getNowFormatDate());
}
}
}