最近编写在页面内通过 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>;
}
}
大功告成!~~
原文:https://segmentfault.com/a/1190000021118085
1.阿里云: 本站现在使用的是阿里云主机,平安/可靠/稳固。点击领取2000米代金券、领会最新阿里云产物的种种优惠流动点击进入
2.腾讯云: 提供云服务器、云数据库、云存储、视频与CDN、域名等服务。腾讯云各种产物的最新流动,优惠券领取点击进入
3.广告同盟: 整理了现在主流的广告同盟平台,若是你有流量,可以作为参考选择适合你的平台点击进入
链接: http://www.fly63.com/article/detial/6639