vue 文件下载支持pdf,jpg,png

第一种 

<div class="item2" @click="handleDownloadFile('文件地址','haohaohao')">下载</div>

// 下载模版
    handleDownloadFile (url, name) {
      if (!url) {
        this.$message.error('暂无文件')
        return false
      }
      // 此方法会不带后缀名,所以要拿到文件的后缀名
      const num = url.split('.')
      const type = num[num.length - 1]
      const link = document.createElement('a')
      fetch(url).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址
        link.href = URL.createObjectURL(blob)
        link.download = `${name}.${type}` // 此处的name是下载的名称
        document.body.appendChild(link)
        link.click()
      })
    }

第二种

页面引入方式

// 方法引到页面
import { staticFileDownload } from '@/utils/index'

// 下载方法
staticFileDownload('文件地址', '名称')



export const staticFileDownload = (href, filename = '文件下载', fileType = 'xlsx') => {
  if (!href) {
    vm.$message.error('未发现文件,请检查');
    return;
  }
  var a = document.createElement("a"); //创建一个a标签
  a.href = href; // 给a标签的href属性值加上地址,如果是项目本地文件,写绝对路径 例如:/static/模板.xlsx
  a.download = `${filename}.${fileType}`; //设置下载文件的文件名,这里加上.xlsx指定文件类型,pdf文件就指定.pdf即可
  a.style.display = "none"; // 隐藏a标签
  document.body.appendChild(a); // 将a标签追加到文档对象中
  a.click(); // 模拟点击了a标签,会触发a标签的href的读取,浏览器就会自动下载了
  a.remove(); // 一次性的,用完就删除a标签
}

第三种文件流下载

页面引入方法
import { exportExcel } from '@/utils/index'


调用方法
exportExcel(res,'名称')

// 导出Excel、zip压缩文件
export const exportExcel = (res, name, loadtype) => {
  let blob = null
  if (loadtype !== '' && loadtype === 'zip') { // zip
    blob = new Blob([res], { type: 'application/zip' })
    const objectURL = URL.createObjectURL(blob)
    const downEle = document.createElement('a')
    downEle.href = objectURL
    downEle.setAttribute('download', `${name}.zip`)
    document.body.appendChild(downEle)
    downEle.click()
  } else { // Excel
    blob = new Blob([res], { type: 'application/vnd.ms-excel' })
    const objectURL = URL.createObjectURL(blob)
    const downEle = document.createElement('a')
    downEle.href = objectURL
    downEle.setAttribute('download', `${name}.xlsx`)
    document.body.appendChild(downEle)
    downEle.click()
    // blob = new Blob([res], { type: 'application/vnd.ms-excel' })
    // const url = window.URL.createObjectURL(blob)
    // const link = document.createElement('a') // 创建a标签
    // link.href = url
    // link.download = name// 重命名文件
    // document.body.appendChild(link)
    // link.click()
    // document.body.removeChild(link)
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学不会•

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值