博客 / 詳情

返回

vue3 點擊下載文件,不打開預覽,已解決

需求背景:vue3項目點擊下載按鈕,下載文件,使用頁面添加a標籤方式會導致不是下載而是打開文件(圖片/pdf)

使用了直接動態添加a標籤的方法,還是會打開預覽

        const url = 'http://192.168.60.59:8888/fayuan/head/4b33a2a1-3911-4586-9878-50373a1fb852.jpg'
        const a = document.createElement('a')
        a.setAttribute('download', '')
        a.setAttribute('href', url)
        a.click() // 自執行點擊事件

解決 :

   setup() {
      const down = () => {
        const url = 'http://file.fayuan.com/tiaojie/wechatImg/website/ali-mini-operation.pdf'
        const filename = '操作指南'
        const x = new XMLHttpRequest()
        x.open('GET', url, true)
        x.responseType = 'blob'
        x.onload = e => {
          // 會創建一個 DOMString,其中包含一個表示參數中給出的對象的URL。這個 URL 的生命週期和創建它的窗口中的 document 綁定。這個新的URL 對象表示指定的 File 對象或 Blob 對象。
          const url = window.URL.createObjectURL(x.response)
          const a = document.createElement('a')
          a.href = url
          a.download = filename
          a.click()
        }
        x.send()
      }
      return {
        down
      }
    }

image.png

user avatar tigerandflower 頭像 ivyzhang 頭像 flymon 頭像 sunhengzhe 頭像 chenychenyu 頭像 zhangxishuo 頭像 mulander 頭像
7 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.