Ant Design Pro 下实现文件下载的实现代码

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Ant Design Pro 下实现文件下载的实现代码

  2021-04-02 我要评论

最近编写在页面内通过 AJAX 请求服务器下载文件遇到一些问题,网上找的资料和介绍大多不健全不系统,最终自己摸索出来的解决方案,先简单写个初稿,后面再详细补充。

表一:前端请求后端下载文件的各种情况

请求方法 请求方式 响应结果
GET 页面跳转 文件对应的 URL
POST AJAX 文件的二进制流

首先,需要在 src/service/api.js 里声明对应请求返回的文件类型:

import request from '@/utils/request';

export async function Download(params = {}) {
 return request(`/api/download`, {
  method: 'POST', // GET / POST 均可以
  data: params,
  responseType : 'blob', // 必须注明返回二进制流
 });
}

然后在对应的 Model 里编写相关请求处理的业务逻辑:

import { message } from 'antd';
import { Download } from '@/services/api';

export default {
  namespace: 'download',
  
  state: {},
  
  effects: {
    *download({ payload, callback }, { call }){
      const response = yield call(Download, payload);
      if (response instanceof Blob) {
        if (callback && typeof callback === 'function') {
           callback(response);
        }
      } else {
        message.warning('Some error messages...', 5);
      }
    }
  },
  
  reducers: {},
}

最后编写页面组件相关业务逻辑,点击下载按钮,派发下载 action 到 model :

import React, { Component } from 'react';
import { Button } from 'antd';
import { connect } from 'dva';

@connect(({ download, loading }) => ({
 download,
 loading: loading.effects['download/download'],
}))
class ExampleDownloadPage extends Component {
  handleDownloadClick = e => {
    e.preventDefault();
    const { dispatch } = this.props;
    const fileName = 'demo.xlsx';
    
    dispatch({
      type: 'download/download',
      payload: {}, // 根据实际情况填写参数
      callback: blob => {
        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, fileName);
        } else {
          const link = document.createElement('a');
          const evt = document.createEvent('MouseEvents');
          link.style.display = 'none';
          link.href = window.URL.createObjectURL(blob);
          link.download = fileName;
          document.body.appendChild(link); // 此写法兼容可火狐浏览器
          evt.initEvent('click', false, false);
          link.dispatchEvent(evt);
          document.body.removeChild(link);
        }
      }
    });
  }
  
  render(){
    const { loading } = this.props;
    
    return <Button 
          loading={loading} 
          icon="download" 
          onClick={this.handleDownloadClick}
        >
         下载
        </Button>;
  }
}

大功告成!~~

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们