前言:項目中須要實現圖片下載功能,第一個想到的是使用a標籤的download屬性來實現,可是在不一樣瀏覽器下測試會發現,有的瀏覽器無效,點擊後直接預覽圖片,因此,上網找到了另一種兼容不一樣瀏覽器的圖片下載的方法,那就是利用canvas來處理圖片,實現下載;前端
1.項目中點擊事件綁定:ios
<a href="#" @click.prevent="downloadIamge(imgsrc, name)"><span>{{name}}</span></a>
2.點擊事件中操做:canvas
downloadIamge (imgsrc, name) { const url = imgsrc this.convertUrlToBase64(url).then((base64) => { const blob = this.convertBase64UrlToBlob(base64) if (getBrowser() === 'IE' || getBrowser() === 'Edge') { window.navigator.msSaveBlob(blob, name) } else { const a = document.createElement('a') const body = document.querySelector('body') a.download = name || 'image' a.href = URL.createObjectURL(blob) a.style.display = 'none' body.appendChild(a) a.click() body.removeChild(a) window.URL.revokeObjectURL(a.href) } }) },
分析:
3.this.convertUrlToBase64(url)就是利用canvas和toDataURL把圖片轉成base64格式並返回跨域
convertUrlToBase64 (url) { return new Promise((resolve, reject) => { const img = new Image() img.crossOrigin = 'Anonymous' img.src = url img.onload = function () { const canvas = document.createElement('canvas') canvas.width = img.width canvas.height = img.height const ctx = canvas.getContext('2d') ctx.drawImage(img, 0, 0, img.width, img.height) const ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase() const dataURL = canvas.toDataURL('image/' + ext) const base64 = { dataURL: dataURL, type: 'image/' + ext, ext: ext } resolve(base64) } }) },
其中:img.crossOrigin = 'Anonymous'是前端對圖片的跨域處理;瀏覽器
4.this.convertBase64UrlToBlob(base64)是將圖片base64流文件轉成blob文件安全
convertBase64UrlToBlob (base64) { const parts = base64.dataURL.split('base64,') const contentType = parts[0].split(':')[1] const raw = window.atob(parts[1]) const rawLength = raw.length const uInt8Array = new Uint8Array(rawLength) for (let i = 0; i < rawLength; i++) { uInt8Array[i] = raw.charCodeAt(i) } return new Blob([uInt8Array], { type: contentType }) },
5.getBrowser()用來判斷瀏覽器,解決瀏覽器兼容性問題:app
import { getBrowser } from '@/utils/utils'
export function getBrowser () { const userAgent = navigator.userAgent if (userAgent.indexOf('OPR') > -1) { return 'Opera' } if (userAgent.indexOf('Firefox') > -1) { return 'FF' } if (userAgent.indexOf('Trident') > -1) { return 'IE' } if (userAgent.indexOf('Edge') > -1) { return 'Edge' } if (userAgent.indexOf('Chrome') > -1) { return 'Chrome' } if (userAgent.indexOf('Safari') > -1) { return 'Safari' } }
6.若是是IE或者Edge瀏覽器,能夠直接使用window.navigator.msSaveBlob(blob, name)完成下載;ide
聲明:因爲ios系統有安全性限制,以上方法在ios上無效;測試
以上就是記錄項目中用到的圖片下載,瀏覽器兼容的問題,涉及到的base64和blob的知識點和原理還不是很清晰,有時間必定要研究一下,整個方法,親測有效;歡迎測用,與意見反饋。this