当前位置: 首页 > news >正文

vue二进制下载

封装axios,/api/request

import axios from 'axios'
import store from '@/store'
import Vue from 'vue'
import { Message, MessageBox } from 'element-ui'import { getToken } from '@/utils/auth'axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const $axios = axios.create({// 设置超时时间timeout: 30000,// 基础url,会在请求url中自动添加前置链接baseURL: process.env.VUE_APP_BASE_API
})Vue.prototype.$http = axios // 并发请求
// 在全局请求和响应拦截器中添加请求状态// 请求拦截器
$axios.interceptors.request.use(config => {if (getToken()) {config.headers.Authorization = getToken() // 请求头部添加tokenconfig.headers.tenantId = store.getters.tenantId}return config},error => {return Promise.reject(error)}
)// 响应拦截器
$axios.interceptors.response.use(response => {if (response.headers['content-type'] === 'application/octet-stream') {return response}// if(response.headers['content-type'] ==="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"){//   return response// }if (response.headers['content-type'] !== 'application/json; charset=utf-8') {return response}const res = response.data || resif (res.success || res.data || res.result_code === 'SUCCESS') {return Promise.resolve(res)} else {return Promise.reject(res)}},error => {let code = ''if (error && error.response) {code = error.response.status}if (code === 401) {return MessageBox.confirm('登录状态已过期,请重新登录','系统提示',{confirmButtonText: '重新登录',type: 'warning'}).then(() => {store.dispatch('LoginOut').then(() => {location.reload() // 为了重新实例化vue-router对象 避免bug})return Promise.reject(new Error('正在为您跳转登录页!'))}).catch(() => {return Promise.reject(new Error('登录过期,请您重新登录!'))})} else if (code === 404) {Message({message: '网络请求不存在!',type: 'error',duration: 5 * 1000})} else if (code === 429) {return Promise.reject(new Error('访问频繁!'))} else if (code === 403) {return Promise.reject(new Error('很抱歉,您的访问权限等级不够,联系管理员!'))} else {return Promise.reject(error || new Error('请求超时'))}}
)// Content-Type
// 'application/json; charset=UTF-8'
// 'Content-Type': 'multipart/form-data' 需要在表单中上传文件以二进制流的方式传递数据
// 'application/x-www-form-urlencoded; charset=UTF-8'  以键值对的方式传递参数
// responseType: 'blob'                 接收文件流
export default $axios

引入/api/request,写接口 

import request from './request'
export function exportReport(data) {return request({method: 'post',url: '/api/ExportExcel/Export',data,responseType: 'blob'})
}

下载

<el-button type="primary" :loading="isDownloading" @click="exportHandle()">导出</el-button>// 导出
exportHandle() {if (this.isDownloading) returnthis.isDownloading = trueconst params = {export_name: 'StockSupplierData',...this.schData}const fileName = '列表' + getTimeStr()exportReport(params).then(res => {const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })if (window.navigator.msSaveOrOpenBlob) {window.navigator.msSaveOrOpenBlob(blob, fileName + '.xlsx')this.isDownloading = false} else {const href = window.URL.createObjectURL(blob) // 创建下载的链接const a = document.createElement('a')a.style.display = 'none'a.download = fileName + '.xlsx'a.href = hrefdocument.body.appendChild(a) // 修复firefox中无法触发clicka.click()document.body.removeChild(a)this.isDownloading = false}}).catch(err => {this.isDownloading = falsethis.$message.error(err.msg || err.message || '导出失败')})
}
// getTimeStr是封装的时间戳
export function getTimeStr() {let date = new Date()let str = '' +date.getFullYear() +padStart((date.getMonth() + 1)) +padStart(date.getDate()) +padStart(date.getHours()) +padStart(date.getMinutes()) +padStart(date.getSeconds())return str
}

或者

axios.post('xxx/api/xxx',{...params},{responselype: 'blob',headers: {'Authorization': getToken()}}
).then(res => {console.log('res', res)
}).catch(err => {console.log('err', err)
})

 

 

 

http://www.lryc.cn/news/120110.html

相关文章:

  • c++QT文件操作
  • Jmeter —— jmeter设置HTTP信息头管理器模拟请求头
  • vue 图片转pdf
  • 20.5 HTML 媒体
  • 科大讯飞分类算法挑战赛2023的一些经验总结
  • 2023年京东按摩仪行业数据分析(京东销售数据分析)
  • 【C语言】进阶指针,超详解,含丰富代码示例
  • wireshark入门指北
  • 18、SQL注入之堆叠及WAF绕过注入
  • nodejs+vue+elementui+express旅游出行指南网站_655ms
  • 【心电图信号压缩】ECG信号压缩与通过三次样条近似重建的ECG信号压缩研究(Matlab代码实现)
  • matlab使用教程(11)—创建随机数
  • 一、安全世界观
  • 爬虫014_文件操作_打开关闭_读写_序列化_反序列化---python工作笔记033
  • 企业前后端分离软件架构如何设计?
  • 生产执行MES系统:提升企业灵活性和响应速度的关键利器
  • 什么是分布式系统,如何学习分布式系统
  • 数据库锁表 Lock wait timeout exceeded; try restarting transaction
  • Oracle 知识篇+分区表上的索引由global改为local注意事项
  • 基于2.4G RF开发的无线游戏手柄解决方案
  • Python之一:基础信息
  • K8S系列文章之 Traefik快速入门
  • RabbitMQ在CentOS下的安装
  • 为什么金鸣识别不做成离线版?
  • 什么是面向对象
  • 记一次前端直接上传图片到oss报错
  • 数据库管理-第九十八期 统计信息是多么重要(20230812)
  • 山西电力市场日前价格预测【2023-08-13】
  • AtCoder Beginner Contest 313D题题解
  • mybatis 中的<![CDATA[ ]]>用法及说明