最近编写在页面内通过 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>; } }
大功告成!~~
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
风云阁资源网 Design By www.bgabc.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
风云阁资源网 Design By www.bgabc.com
暂无评论...
更新日志
2024年09月20日
2024年09月20日
- 群星.2022-一不小心喵上你原声大碟【TME影音】【FLAC分轨】
- 《战锤40K星际战士2》卡在正在加入服务器解决方法
- 《勇者斗恶龙怪物仙境3》玩法内容介绍
- 《幸福工厂》无限报错解决方法
- 交错战线原始交易所推荐角色一览
- 战锤40K星际战士2战术职业介绍|战术职业技能效果一览
- 战锤40K星际战士2突击职业介绍|突击职业技能效果一览
- [妙音金曲]群星《悲情咖啡屋》(黑胶)2CD[DTS-WAV]
- 阿兰·达瓦卓玛《A-Lan阿兰唯美歌姬》2CD[DTS-WAV]
- 【小提琴】陈立新《思乡曲》2004[FLAC+CUE]
- 《战地》新作明年初大规模测试!EA已内部测试一年
- 《GTAOL》PC版时隔多年更新反作弊!小助手宣布跑路
- EA称AI是其业务核心!能提高开发效率、节约成本
- 卫华.1990-太阳升【BMG】【WAV+CUE】
- 呼吸乐队.1992-THEBREATHING【深飞】【WAV+CUE】