任意文件下載包含https的圖片


使用a標簽進行下載

 <a href="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png">下載</a>

出現的問題

如果使用a標簽指向一個圖片,
你會發現點擊鏈接時它會直接在瀏覽器中打開圖片並顯示.
並不是下載到本地,與我們的初衷相違背
我們應該如何去解決這個問題了。

嘗試了將圖片轉成Base64或者Blob的辦法

function downloadImgByBlob(url) {
    var img = new Image()
    img.onload = function() {
        var canvas = document.createElement('canvas')
        canvas.width = img.width
        canvas.height = img.height
        var ctx = canvas.getContext('2d')
        // 將img中的內容畫到畫布上
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
        // 將畫布內容轉換為Blob
        canvas.toBlob((blob) => {
            // blob轉為同源url
            var blobUrl = window.URL.createObjectURL(blob)
            // 創建a鏈接
            var a = document.createElement('a')
            a.href = blobUrl
            a.download = ''
            // 觸發a鏈接點擊事件,瀏覽器開始下載文件
            a.click()
        })
    }
img.src = url
// 必須設置,否則canvas中的內容無法轉換為blob
img.setAttribute('crossOrigin', 'Anonymous')
}

function downloadImgByBase64(url) {
    var img = new Image()
    img.onload = function() {
        var canvas = document.createElement('canvas')
        canvas.width = img.width
        canvas.height = img.height
        var ctx = canvas.getContext('2d')
        // 將img中的內容畫到畫布上
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
        // 將畫布內容轉換為base64
        var base64 = canvas.toDataURL()
        // 創建a鏈接
        var a = document.createElement('a')
        a.href = base64
        a.download = ''
        // 觸發a鏈接點擊事件,瀏覽器開始下載文件
        a.click()
    }
    img.src = url
    // 必須設置,否則canvas中的內容無法轉換為base64
    img.setAttribute('crossOrigin', 'Anonymous')
}

出現的問題

上述兩種方法效果都不太理想。因為這兩種方法僅支持生成jpeg和png格式圖片。如果是gif圖,僅能顯示第一幀的內容

通過XMLHttpRequest()請求圖片鏈接

<button @click="myFileDownLoad"> 下載</button>

myFileDownLoad(){
  var x=new XMLHttpRequest();
  x.open("GET", "https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1986179278,1118313821&fm=27&gp=0.jpg", true);
  x.responseType = 'blob';
  x.onload=function(){
      var url = window.URL.createObjectURL(x.response)
      var a = document.createElement('a');
      a.href = url
      a.download = '你的下載'
      a.click()
  }
  x.send();
}
該示例的思路是,通過XMLHttpRequest()請求圖片鏈接,然后獲取返回的Blob。那結合上面下載圖片的方法,就能下載圖片了:
通過這種方法下載圖片,gif圖也能夠顯示正常了。
注意,上述方法能夠兼容大部分瀏覽器,但是不兼容IE瀏覽器(不支持download屬性)。要兼容IE瀏覽器需要用其他辦法。
下載的鏈接好像要是https的才行 (我下載的都是https的圖片)

ps:語法
objectURL = URL.createObjectURL(object);
參數object;用於創建 URL 的 File 對象、Blob 對象或者 MediaSource(媒體資源) 對象。
返回值:該URL可用於指定源 object的內容

文件下載 既可以下載圖片又可以任意文件類型[xls,word,mp4]

function downLoad(item) {
//filePathUrl是一個https的地址哈。
            if (item.filePathUrl) {
                // 下載https的圖片
                let fileType = item.fileName.split('.').pop()
                let canDownFileType = ['jpg', 'png', 'gif', 'webp', 'jpeg']
                if (canDownFileType.indexOf(fileType) != -1) {
                    // 下載的是圖片
                    var x = new XMLHttpRequest()
                    x.open('GET', item.filePathUrl, true)
                    x.responseType = 'blob'
                    x.onload = function (e) {
                        var url = window.URL.createObjectURL(x.response)
                        var a = document.createElement('a')
                        a.href = url
                        a.download = item.fileName //圖片的下載名稱
                        a.click()
                    }
                    x.send()
                } else {
                    // // 下載的是文件類型的,
                    var url = item.filePathUrl
                    var xhr = new XMLHttpRequest()
                    xhr.open('GET', url, true)
                    xhr.responseType = 'blob'
                    xhr.onload = function () {
                        if (xhr.status === 200) {
                            var blob = xhr.response
                            var link = document.createElement('a')
                            var body: any = document.querySelector('body')
                            link.href = window.URL.createObjectURL(blob)
                            link.download = item.fileName
                            link.style.display = 'none'
                            body.appendChild(link)
                            link.click()
                            body.removeChild(link)
                        }
                    }
                    xhr.send()
                }
            } else {
                window.$message.error('資源地址不存在')
            }
        }

繼續優化可以通過http下載任意文件

function downLoad = (url, item) => {
	var xhr = new XMLHttpRequest()
	xhr.open('GET', url, true)
	xhr.responseType = 'blob'
	xhr.onload = function () {
		if (xhr.status === 200) {
			var blob = xhr.response
			var link = document.createElement('a')
			var body: any = document.querySelector('body')
			link.href = window.URL.createObjectURL(blob)
			link.download = item.name
			link.style.display = 'none'
			body.appendChild(link)
			link.click()
			body.removeChild(link)
		}
	}
	xhr.send()
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM