Ant Design Pro 下实现文件下载

更新日期: 2019-10-26阅读: 3.5k标签: ant

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


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

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

首先,需要在 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>;
    }
}

大功告成!~~

原文:https://segmentfault.com/a/1190000021118085

链接: https://www.fly63.com/article/detial/6639

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!