• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

vue文件下载功能通过和后端对接接口实现

武飞扬头像
刚刚好ā
帮助1

实现目标:点击下载按钮,浏览器下方出现下载的文件,word文件将下载为word文件格式,不会进行pdf的转换。

实现效果:

学新通

实现方法:

1.后端swagger中:

学新通

 2.api的js文件中:

  1.  
    export function planDownloadById(param) {
  2.  
    return request({
  3.  
    url: '/xxxx/xxxx/download',
  4.  
    method: 'post',
  5.  
    data: param,
  6.  
    responseType: 'blob', // 必须要写
  7.  
    headers: {
  8.  
    'Content-Type': 'application/json;charset=UTF-8'
  9.  
    }
  10.  
    });
  11.  
    }

3.vue文件中:

引入api文件中的下载接口

import { planDownloadById } from '@/api/xxxx/index'

template中:

  1.  
    <template slot-scope="scope">
  2.  
    <el-button @click="downloadPlan(scope.row)" type="text" size="small" style="margin-right: 20px">
  3.  
    <i class="el-icon-download"></i>
  4.  
    下载
  5.  
    </el-button>
  6.  
    </template>

methods中:

  1.  
    downloadPlan(row) {
  2.  
    // 下载文件的名称
  3.  
    let filePathArray = row.filePath.split('/')
  4.  
    let fileName = filePathArray[filePathArray.length - 1]
  5.  
    // 参数拼接
  6.  
    let param = new FormData()
  7.  
    param.append('id', row.id)
  8.  
    // 调用接口
  9.  
    planDownloadById(param).then((res) => {
  10.  
    if (res.status == 200) {
  11.  
    const link = document.createElement('a') // 创建a标签
  12.  
    const blo = new Blob([res.data], { type: res.data.type }) // 设置下载格式
  13.  
    link.style.display = 'none'
  14.  
    const url = window.URL.createObjectURL(blo)
  15.  
    link.href = url
  16.  
    link.setAttribute('download', fileName)
  17.  
    document.body.appendChild(link)
  18.  
    link.click() // 触发下载
  19.  
    window.URL.revokeObjectURL(url) // 释放掉blob对象
  20.  
    document.body.removeChild(link)
  21.  
    this.refreshData() // 刷新页面
  22.  
    } else {
  23.  
    this.$message.warning('请稍后再试')
  24.  
    }
  25.  
    })
  26.  
    },
学新通

这样就实现了文件的下载功能。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhggeiek
系列文章
更多 icon
同类精品
更多 icon
继续加载