はじめに: 画像のダウンロード機能をプロジェクトに実装する必要がある場合、最初に思いつくのは、 a タグの download 属性を使用することです。ただし、別のブラウザーでテストすると、一部のブラウザーでは問題が発生することがわかります。は無効であり、クリックすると画像が直接プレビューされます。そのため、さまざまなブラウザーと互換性のある画像をダウンロードする別の方法を見つけました。それは、キャンバスを使用して画像を処理してダウンロードすることです。
1. プロジェクト内のイベント バインディングをクリックします。
<a href=# @click.prevent=downloadIamge(imgsrc, name)><span>{{name}}</span></a>2. クリックイベントでの動作:
downloadIamge (imgsrc, name) { const url = imgsrc this.convertUrlToBase64(url).then((base64) => { const blob = this.convertBase64UrlToBlob(base64) if (getBrowser() === 'IE' || getBrowser( ) === 'エッジ') { 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 = 'なし' 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((解決、拒否) => { const img = new Image() img.crossOrigin = 'Anonymous' img.src = url img.onload = function () { const Canvas = document.createElement ('キャンバス') 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、タイプ: 'image/' + ext、ext: ext }solve(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() は、ブラウザを特定し、ブラウザの互換性の問題を解決するために使用されます。
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) { 'Safari' を返す }}6. IE または Edge ブラウザの場合は、window.navigator.msSaveBlob(blob, name) を直接使用してダウンロードを完了できます。
免責事項: iOS システムのセキュリティ制限のため、上記の方法は iOS では無効です。
上記は、記録プロジェクトで使用される画像のダウンロードとブラウザの互換性の問題ですが、base64 と blob に関連する知識ポイントと原則はまだあまり明確ではありません。時間があるときに全体的な方法を学習する必要があります。 ; テストとフィードバックを歓迎します。皆様もVeVb Wulin Networkを応援していただければ幸いです。