关于javascript:js保存图片兼容ie

36次阅读

共计 2013 个字符,预计需要花费 6 分钟才能阅读完成。

应用 window.navigator.userAgent 获取浏览器你内核,而后判断是不是 ie/edge 内核

// 判断浏览器类型
function myBrowser() {
    var sBrowser = null
    var sUsrAg = window.navigator.userAgent
    if (sUsrAg.indexOf('Firefox') > -1) {sBrowser = 'FF'} else if (sUsrAg.indexOf('Opera') > -1 || sUsrAg.indexOf('OPR') > -1) {sBrowser = 'Opera'} else if (sUsrAg.indexOf('Trident') > -1) {sBrowser = 'IE'} else if (sUsrAg.indexOf('Edge') > -1) {sBrowser = 'Edge'} else if (sUsrAg.indexOf('Chrome') > -1) {sBrowser = 'Chrome'} else if (sUsrAg.indexOf('Safari') > -1) {sBrowser = 'Safari'} else {sBrowser = 'unknown'}
    return sBrowser
}

如果是 ie/edge 内核

// IE 浏览器图片保留本地
function SaveAs5(url, fileName) {var bstr = atob(url.split(',')[1])
    var n = bstr.length
    var u8arr = new Uint8Array(n)
    while (n--) {u8arr[n] = bstr.charCodeAt(n)
    }
    var blob = new Blob([u8arr])
    window.navigator.msSaveOrOpenBlob(blob, fileName)
}

其余浏览器

// 谷歌,360 极速等浏览器下载
function download(src, fileName) {var aLink = document.createElement('a');
    aLink.download = fileName;
    aLink.href = src 
    aLink.click();};

残缺 js 代码

// 下载前先判断浏览器的内核
function oDownLoad(url, fileName) {if (myBrowser() == "IE" || myBrowser() == "Edge") {SaveAs5(url, fileName);
    } else {download(url, fileName);
    }
}

// IE 浏览器图片保留本地
function SaveAs5(url, fileName) {var bstr = atob(url.split(',')[1])
    var n = bstr.length
    var u8arr = new Uint8Array(n)
    while (n--) {u8arr[n] = bstr.charCodeAt(n)
    }
    var blob = new Blob([u8arr])
    window.navigator.msSaveOrOpenBlob(blob, fileName)
}

// 谷歌,360 极速等浏览器下载
function download(src, fileName) {
    // 须要转成 blob,base64 下载大图会超出 href 的限度,导致下载失败
    var aLink = document.createElement('a');
    aLink.download = fileName;
    // var blob = dataURLtoBlob(src);
    aLink.href = src // URL.createObjectURL(blob);
    aLink.click();};

// 判断浏览器类型
function myBrowser() {
    var sBrowser = null
    var sUsrAg = window.navigator.userAgent
    if (sUsrAg.indexOf('Firefox') > -1) {sBrowser = 'FF'} else if (sUsrAg.indexOf('Opera') > -1 || sUsrAg.indexOf('OPR') > -1) {sBrowser = 'Opera'} else if (sUsrAg.indexOf('Trident') > -1) {sBrowser = 'IE'} else if (sUsrAg.indexOf('Edge') > -1) {sBrowser = 'Edge'} else if (sUsrAg.indexOf('Chrome') > -1) {sBrowser = 'Chrome'} else if (sUsrAg.indexOf('Safari') > -1) {sBrowser = 'Safari'} else {sBrowser = 'unknown'}
    return sBrowser
}

// 间接援用
oDownLoad(base64 文件,'aa.jpg')

dataURLtoBlob 你们可能用不了,想其余办法转吧

正文完
 0