vue 后台返回文件流实现下载功能

950 阅读1分钟

form标签

写法一

<el-button  type="primary" size="small" class="btnFloatRight" @click="downloadUrl">导出</el-button>

import $ from 'jquery'

downloadUrl() {
  const selectData = this.selectPIStore
  const $iframe = $('<iframe id="rfFrame" name="rfFrame" src="about:blank" style="display:none;"/>')
  const $form = $('<form target="rfFrame" method="post" />')
  $form.attr('action', 'api/mksecurity-admin/plan/excel')
  selectData.forEach(function(i, v) {
    $form.append('<input type="hidden" name="planIdList" value="' + i.id + '" />')
  })
  $iframe.append($form)
  $(document.body).append($iframe)
  $form[0].submit()
}

写法二

<!--template-->
<form id="cgForm" :action="formatUrl('/api/jobPoolPlan/exportToExcel',searchForm)" method="post" style="display: none;">
    <input :value="enableTitles" name="enableTitles" type="hidden">
    <input :value="getToken" name="access_token">
</form>

<!--methods-->
const form = document.getElementById('cgForm')
setTimeout(() => {
    form.submit()
}, 2000)

Blob

// axios请求头 'responseType: 'blob'
/**
   * 头像展示、文件下载
   * 接口返回文件流
*/
const getFilestream = (url, path, pars) => {
  return new Promise((resolve, reject) => {
    axios.defaults.headers.common.Authorization = 'Bearer ' + LoginUser.ticket
    const _path = path === '' || path == null ? '' : '/' + path
    axios({
      method: 'GET',
      url: url + _path,
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      },
      responseType: 'blob',
      params: pars
    }).then(function (response) {
      expiresOut(response)
      resolve(response.data)
    })
      .catch(error => {
        // eslint-disable-next-line no-unused-expressions
        NProgress.done
        message.alert('系统错误:' + error)
      })
  })
}

/**
   * 通用方法封装 文件下载
   * annexId:文件id
   * fileName: 文件名
*/
export async function fileDownload (_this, annexId, fileName) {
  const params = {
    annexId: annexId
  }
  const res = await ajaxHelp.getFilestream(
    api.apiUrlCommon.download,
    null,
    params
  )
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    // for IE
    const blob = new Blob([res], {
      type: 'application/vnd.ms-excel;charset=utf-8'
    })
    window.navigator.msSaveOrOpenBlob(blob, fileName)
  } else {
    const src = window.URL.createObjectURL(res)
    const a = document.createElement('a')
    document.body.appendChild(a)
    a.href = src
    a.download = fileName
    a.click()
    window.URL.revokeObjectURL(src)
  }
}
import { fileDownload } from '@/util/common'

// fileName要带后缀名
const fileName = scope.row.annex.name + '.' + scope.row.annex.suffix
fileDownload(this, scope.row.annex.id, fileName)