前端下载pdf、excel以及图片

102 阅读1分钟

我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!

安装axios即可

npm i axios -S

上代码

<template>
    <div>
	<button @click=“download”>下载文件</button>
    </div>
</template>
<script>
    import axios from 'axios'
    export default {
       data(){
           return {}
	},
	methods:{
            downloadFile(blob,filename = '未命名'){
		// 以下是兼容ie
                if(navigator.msSaveBlob){
                                                                                                   window.navigator.msSaveOrOpenBlob(blob,filename)
		}
		// 以上是兼容ie
                const link = document.createElement('a')
		const binaryData = []
		binaryData.push(blob)
		link.href = window.URL.createObjectURL(new Blob(binaryData))
		link.download = filename
		link.style.display = 'none'
		document.body.appendChild(link)
		link.click()
		document.body.removeChild(link)
		},
		download(){
                    axios({
			// 由于axios会自动拼接服务器地址,请把文件或图片放置在静态资源里 我这里放到了 public/static 里面
			url:'/static/1.excel',
			method:'get'responseType:'blob'
                    }).then((res)=>{
			this.downloadFile(res.data,`1.excel`)
                    })
		}
            }
	}
</script>

若将前端包打到后端包里进行部署上线,出现404的情况,请将 url 拼接包的名称name。即 url:'/name/static/1.excel',若不是请忽略