【Ant Design of Vue】文件下载

一、需求

  • 实现文件的下载功能

二、技术栈

  • 前端框架:vue2
  • 前端UI框架:Ant Design of Vue(v1.7.8)

三、代码

<template>
  <a-button type="primary" @click="onClick">点击下载</a-button>
</template>

<script>
import api from '@/api/api.js';
export default {
    
    
  methods: {
    
    
    onClick() {
    
    
      // 调用文件下载接口
      api.downloadEleMouldFile().then((res) => {
    
    
      	// 创建a标签
        const link = document.createElement('a');
        // 构造一个blob对象来处理数据, 并设置文件类型
        const url = window.URL.createObjectURL(new Blob([res]), {
    
    
          type: 'application/vnd.ms-excel',
        });
        // 文件类型可写可不写,如果不知道文件类型该使用什么,直接不写即可
        // const url = window.URL.createObjectURL(new Blob([res]));
        // 指定下载链接
        link.href = url;
        // 指定下载文件名
        link.download = '泡泡哥牛逼.xls';
        // 把a标签加到页面中
        document.body.appendChild(link);
        // 触发a标签下载
        link.click();
        // 下载完成移除元素
        document.body.removeChild(link);
        // 释放掉blob对象
        window.URL.revokeObjectURL(url);
      });
    },
  },
};
</script>

<style></style>
// 接口定义文件(api.js)
function downloadEleMouldFile(parameter) {
    
    
  return request({
    
    
    url: api.downloadEleMouldFile,
    method: 'post',
    params: parameter,
    responseType: 'blob'  // 必须设置
	// 服务器响应的数据类型有: 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream', 默认是'json'
  });
}

四、效果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43417844/article/details/129956584