美文网首页前端开发那些事儿
vue图片,pdf等资源文件下载到本地(同源和跨域两种方法)

vue图片,pdf等资源文件下载到本地(同源和跨域两种方法)

作者: small_zeo | 来源:发表于2021-07-05 15:59 被阅读0次

    同源(访问的网站域名与服务器域名一致)才能用方法一下载

    方法一: 同源资源文件下载

    const downLoadFunc = (imgSrc, imgName) => {
           if (!imgSrc)  return
            let url = window.URL.createObjectURL(new Blob([imgSrc]))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', imgName)
            document.body.appendChild(link)
            link.click()
    }
    

    方法二: 跨域资源图片下载

    const downLoadFunc = (imgSrc, imgName) => {
            if (!imgSrc)  return
            let image = new Image() 
            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 link = document.createElement('a') 
                let event = new MouseEvent('click') 
                link.download = imgName || (new Date().getTime())  
                link.href = url  
                link.dispatchEvent(event)  
            }
            image.src = imgSrc
    }
    

    方法三: 跨域资源pdf下载

    const downLoadFunc = (imgSrc, imgName) => { 
            if (!imgSrc)  return
            fetch(imgSrc).then(function (response) {
                response.arrayBuffer().then(res => {
                    let type = 'application/pdf;charset-UTF-8' // 资源类型pdf
                    // 常见资源类型 
                       // 1.excel: type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                       // 2.图片: type = "image/*"
                       // 3.视频: type = "video/*"
                       // 4.音频: type = "audio/*"
                       // 5.pdf: type = "application/pdf;charset-UTF-8"
                    //
                    let blob = new Blob([res], {type: type})
                    let objectUrl = URL.createObjectURL(blob)
                    let link = document.createElement('a')
                    link.style.display = 'none'
                    link.href = objectUrl
                    link.setAttribute('download', imgName)
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link)
                })
            })
    }
    
    

    相关文章

      网友评论

        本文标题:vue图片,pdf等资源文件下载到本地(同源和跨域两种方法)

        本文链接:https://www.haomeiwen.com/subject/fbhiultx.html