【vue】---- 前端實現下載Excel功能


1、實現思路:

html5 中,在 a 標簽上添加 download 屬性可以實現文件下載。

<a download="文件名" href="文件下載接口地址"></a>   

 

2、在這次項目中,點擊非a標簽按鈕下載文件,通過創建a標簽來實現。

<script>
  export default {
    data() {
      return {
        downFileName: 'user_dowm',  // 自定義下載的文件名
      }
    },
    methods:{
   // 點擊下載事件 downLoadFail(data) {
this.$axios({ headers: { 'Content-Type': 'application/json' }, url: '/user/download', data: data, responseType: 'blob', method: 'get' }).then(res => { if (typeof window.chrome !== 'undefined') { // Chrome version const blob = new Blob([res], { type: 'application/vnd.ms-excel' }) const urls = window.URL.createObjectURL(blob) const a = document.createElement('a') // 生成虛擬a標簽 a.href = urls a.download = this.downFileName + '.xlsx' a.click() document.body.removeChild(a) // 下載完成移除元素 window.URL.revokeObjectURL(urls) // 釋放掉blob對象 } else if (typeof window.navigator.msSaveBlob !== 'undefined') { // IE version const blob = new Blob([res], { type: 'application/force-download' }) window.navigator.msSaveBlob(blob, this.downFileName) } else { // Firefox version const file = new File([res], this.downFileName, { type: 'application/force-download' }) window.open(URL.createObjectURL(file)) } }).catch(err => { console.log(err) }) } } } </script>

 

注:發現一篇實用的前端下載文件的參考,貼上~

https://www.jianshu.com/p/48ad4346fe4b

 


免責聲明!

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



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