vue使用axios下载文件

方法一:直接在使用axios请求中处理

api文件:

import axios from 'axios'

// 下载文件
export const exportFile = (params: any) => {
  return axios({
    url: `/dow/${params.fileCategory}/${params.filePath}`,
    method: 'get',
    params,
    responseType: 'blob'
  }).then(res => {
    let blob = new Blob([res.data],{type: res.headers['content-type']});
    // 创建新的URL并指向File对象或者Blob对象的地址
    const blobURL = window.URL.createObjectURL(blob)
    // 创建a标签,用于跳转至下载链接
    const tempLink = document.createElement('a')
    tempLink.style.display = 'none'
    tempLink.href = blobURL
    const contentDisposition = res.headers['content-disposition'] || `attachment;filename=${params.filePath}`;
    tempLink.setAttribute('download', decodeURI(contentDisposition.split(';')[1].split('=')[1]))
    // 兼容:某些浏览器不支持HTML5的download属性
    if (typeof tempLink.download === 'undefined') {
      tempLink.setAttribute('target', '_blank')
    }
    // 挂载a标签
    document.body.appendChild(tempLink)
    tempLink.click()
    document.body.removeChild(tempLink)
    // 释放blob URL地址
    window.URL.revokeObjectURL(blobURL)
  });
}

export default {
  exportFile
}

调用的文件:

import common from '@/api/common'

// 下载文件
const download = (record) => {
  //fileCategory:文件夹名    filePath:文件路径
  common.exportFile({'fileCategory':'identify','filePath':record.filePath})
}

方法2:通过axios二次封装时处理

request文件:

import { App } from 'vue'
import storage from 'store'
import router from '@/router'
import { regAxios } from './install'
import { message } from 'ant-design-vue'
import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'

// 创建axios实例

const request = axios.create({
  baseURL: import.meta.env.VITE_REQUEST_BASE_URL as string,
  timeout: 6000
})

/**
 * @desc: 异常拦截处理器
 * @param { Object } error 错误信息
 */
const errorHandler = (error: AxiosError): AxiosError | Promise<AxiosError> => {
  message.error(error.message)
  return Promise.reject(error)
}

/**
 * @desc: 请求发送前拦截
 * @param { Object } config 配置参数
 */
request.interceptors.request.use((config: AxiosRequestConfig): AxiosRequestConfig => {
  config.headers['token'] = storage.get('token') || ''
  return config
}, errorHandler)


/**
 * @desc: 服务端响应后拦截
 * @param { Object } response 返回的数据
 */
request.interceptors.response.use((response: AxiosResponse): AxiosResponse | Promise<AxiosResponse> => {
  if (response.config.responseType === "blob") {
    let blob = new Blob([response.data],{type: response.headers['content-type']});
    // 创建新的URL并指向File对象或者Blob对象的地址
    const blobURL = window.URL.createObjectURL(blob)
    // 创建a标签,用于跳转至下载链接
    const tempLink = document.createElement('a')
    tempLink.style.display = 'none'
    tempLink.href = blobURL
    const contentDisposition = response.headers['content-disposition'] || 'attachment;filename=Download';
    tempLink.setAttribute('download', decodeURI(contentDisposition.split(';')[1].split('=')[1]))
    // 兼容:某些浏览器不支持HTML5的download属性
    if (typeof tempLink.download === 'undefined') {
      tempLink.setAttribute('target', '_blank')
    }
    // 挂载a标签
    document.body.appendChild(tempLink)
    tempLink.click()
    document.body.removeChild(tempLink)
    // 释放blob URL地址
    window.URL.revokeObjectURL(blobURL)
  } else if (response.data.code === 200 || response.data.error === false) {
    return response
  } else if (response.data.code === -401) {
    // 登录失效
    storage.remove('token')
    router.push({ path: '/login', query: { redirect: router.currentRoute.value.fullPath } })
    return Promise.reject(response)
  } else {
    return Promise.reject(response)
  }
}, errorHandler)

export const globalAxios = {
  install (app: App) {
    app.use(regAxios, request)
  }
}

export default request
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue使用axios下载文件的方法可以通过以下步骤来实现: 1. 首先,需要在Vue项目中导入axios和common模块。可以通过以下代码实现导入: ```javascript import axios from 'axios'; import common from '@/api/common'; ``` 2. 接下来,可以定义一个下载文件的方法,比如`download`。该方法可以接收一个参数`record`,表示要下载文件的相关信息。在该方法中,可以调用`common.exportFile`方法来下载文件。此方法接收一个对象作为参数,其中包括文件夹名(`fileCategory`)和文件路径(`filePath`)。具体代码如下: ```javascript const download = (record) => { common.exportFile({'fileCategory':'identify','filePath':record.filePath}); } ``` 3. 在后台的Spring Boot接口中,可以定义一个用于下载附件的接口。可以通过`@RequestMapping`注解定义该接口的URL和请求方法类型。在该接口的方法中,可以使用`@PathVariable`注解来获取参数。具体代码如下: ```java @Transactional @ApiOperation(notes = "下载附件接口", value = "下载附件接口", httpMethod = "GET", produces = "application/json") @RequestMapping(value = "/downloadAttachFile/{leaderPhone}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8") public Result downloadAttachFile(HttpServletResponse response, @ApiParam(name = "leaderPhone", required = true, value = "leaderPhone")@PathVariable("leaderPhone") String leaderPhone ) throws UnsupportedEncodingException { return userService.downloadAttachFile(response,leaderPhone); } ``` 4. 在Excel pom依赖中,需要添加poi和poi-ooxml的依赖。具体的依赖代码如下: ```xml <!-- excel依赖 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.16</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.16</version> </dependency> ``` 通过以上步骤,你可以在Vue使用axios下载文件。首先导入axios和common模块,然后定义一个下载文件的方法,最后在后台接口中实现文件下载功能,并添加相关的Excel依赖。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [vue使用axios下载文件](https://blog.csdn.net/qq_43892230/article/details/129811949)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [vue + axios实现文件下载](https://blog.csdn.net/gaopinqiang/article/details/107350563)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

未名'

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

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

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

打赏作者

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

抵扣说明:

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

余额充值