前端實現訪問img地址直接下載

    handleDownload(row) {
      const { id, pictureurllist } = row
      if (pictureurllist && pictureurllist[0]) {
        const { fileservicepath, filesuffix, title } = pictureurllist[0]
        const isImg = ['jpg', 'jpeg', 'png'].includes(filesuffix)
        console.log(isImg)
        if (isImg) {
          this.downloadIamge(fileservicepath, title)
        } else {
          window.open(fileservicepath)
        }
      }
    },
    downloadIamge(imgsrc, name) {
      let image = new Image()
      // 解決跨域 Canvas 污染問題
      image.setAttribute('crossOrigin', 'anonymous')
      image.onload = function () {
        let canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        let context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        let url = canvas.toDataURL('image/png') //獲得圖片的base64編碼數據
        let a = document.createElement('a') // 生成一個a元素
        let event = new MouseEvent('click') // 建立一個單擊事件
        a.download = name || 'photo' // 設置圖片名稱
        a.href = url // 將生成的URL設置爲a.href屬性
        a.dispatchEvent(event) // 觸發a的單擊事件
      }
      image.src = imgsrc
    }
相關文章
相關標籤/搜索