request.ts
/*
* @Author: zhangzc
* @Email: zhangzc2@guahao.com
* @Date: 2019-07-05 16:51:39
* @Last Modified by: zhangzc
* @Last Modified time: 2020-09-13 17:55:27
* @Description: 公共请求封装
* @Route: Route
*/
import Axios from 'axios';
import { notification } from 'antd';
import Configs from '@/configs';
const codeMessage = {
200: '服务器成功返回请求的数据。',
201: '新建或修改数据成功。',
202: '一个请求已经进入后台排队(异步任务)。',
204: '删除数据成功。',
400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
401: '用户没有权限(令牌、用户名、密码错误)。',
403: '用户得到授权,但是访问是被禁止的。',
404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
406: '请求的格式不可得。',
410: '请求的资源被永久删除,且不会再得到的。',
422: '当创建一个对象时,发生一个验证错误。',
500: '服务器发生错误,请检查服务器。',
502: '网关错误。',
503: '服务不可用,服务器暂时过载或维护。',
504: '网关超时。',
};
const request = async (config: any) => {
const { method, params, independent, url, timeout, headers: headerInfo, ...other } = config;
const { baseUrl } = Configs;
const token = localStorage.getItem('token');
const headers = {
token,
platformId: 1,
...headerInfo,
};
if (!/\/user\/info/.test(url)) {
headers['sf-admin-token'] = localStorage.getItem('sf-admin-token');
headers['yf-admin-token'] = localStorage.getItem('sf-admin-token');
}
// 创建axios实例
const axiosIns = Axios.create();
let options = {
headers,
baseURL: baseUrl,
url,
withCredentials: true,
...other,
timeout: timeout || 1 * 60 * 1000,
};
if (method === 'post') {
options = {
...options,
method: 'post',
data: params,
};
} else if (method === 'put') {
options = {
...options,
method: 'put',
data: params,
};
} else {
options = {
...options,
method: 'get',
params,
};
}
const response = await axiosIns(options)
.then((res) => {
const { code, message } = res.data;
// independent 存在做单独异常处理,其余走统一业务处理
if (independent) return res;
if (code !== '0') {
notification.error({
message: `请求错误 ${code}`,
description: message,
});
if (code === '12009') {
localStorage.removeItem('token');
localStorage.removeItem('sf-admin-token');
localStorage.removeItem('userPermission');
}
}
return res.data;
})
.catch((error) => {
const { response: errRes } = error;
if (errRes && errRes.status) {
const errorText = codeMessage[errRes.status] || errRes.statusText;
const { status, url: fetchUrl } = errRes;
notification.error({
message: `请求错误 ${status}: ${fetchUrl}`,
description: errorText,
});
} else if (!errRes) {
notification.error({
description: '您的网络发生异常,无法连接服务器',
message: '网络异常',
});
}
});
return response;
};
export default request;
?
?service.ts?
export const uploadFile = (params: any): Promise<any> => {
const form = new FormData();
form.append('files', params.file);
return request({
method: 'post',
url: `/api/file-center/storage/upload`,
body: { ...params },
params: form,
type: 'form',
});
};
form.tsx?
import React, { Component } from 'react'
import { Form, Row, Col, Input, Button, Select, Radio, Upload, message } from 'antd'
import styles from '../../index.less'
import _ from 'lodash';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { getStaffsList, saveBaseInfo, uploadStoreFile, getHeadStoreList, getStoreDetail } from '../../service'
import { FormInstance } from 'antd/es/form';
interface IState {
pictureUrl: string,// 图片上传
loading: boolean,
}
class BaseInfo extends Component<IProps, IState> {
formRef = React.createRef<FormInstance>();
constructor(props: IProps) {
super(props);
this.state = {
pictureUrl: '',// 图片上传
loading: false,
}
}
beforeUpload = (file: any) => {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
message.error('请上传 JPG/JPEG/PNG 类型的文件!');
}
const isLt2M = file.size / 1024 < 2000;
if (!isLt2M) {
message.error('文件不能大于200k!');
}
return isJpgOrPng && isLt2M;
}
customRequest = (info: any) => {
this.setState({ loading: true });
uploadStoreFile(info).then(res => {
if(res.code && res.code === '0'){
console.log(res.data[0].fileUrl)
this.setState({
pictureUrl: res.data[0].fileUrl,
loading: false
})
this.formRef.current!.setFieldsValue({
pictureUrl: this.state.pictureUrl,
})
}
})
}
render() {
const uploadButton = (
<div>
{loading ? <LoadingOutlined /> : <PlusOutlined />}
<div style={{ marginTop: 8 }}></div>
</div>
);
return (
<div>
<Form>
<Row>
<Col span={12}>
<Form.Item name="pictureUrl" label="图片上传">
<Upload
listType="picture-card"
showUploadList={false}
beforeUpload={this.beforeUpload}
customRequest={this.customRequest}
// onChange={this.handleChangeFile}
>
{pictureUrl ? <img src={pictureUrl} alt="avatar" style={{ maxWidth: '100%', maxHeight: '100%' }} /> : uploadButton}
</Upload>
</Form.Item>
<span>图片上传(限1张,jpg,jpeg,png文件类型)</span>
</Col>
</Row>
</Form>
</div>
)
}
|