当前位置:   article > 正文

【React】antd上传文件组件customRequest自定义上传解析_antd customrequest

antd customrequest

request.ts

  1. /*
  2. * @Description: 公共请求封装
  3. * @Route: Route
  4. */
  5. import Axios from 'axios';
  6. import { notification } from 'antd';
  7. import Configs from '@/configs';
  8. const codeMessage = {
  9. 200: '服务器成功返回请求的数据。',
  10. 201: '新建或修改数据成功。',
  11. 202: '一个请求已经进入后台排队(异步任务)。',
  12. 204: '删除数据成功。',
  13. 400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
  14. 401: '用户没有权限(令牌、用户名、密码错误)。',
  15. 403: '用户得到授权,但是访问是被禁止的。',
  16. 404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
  17. 406: '请求的格式不可得。',
  18. 410: '请求的资源被永久删除,且不会再得到的。',
  19. 422: '当创建一个对象时,发生一个验证错误。',
  20. 500: '服务器发生错误,请检查服务器。',
  21. 502: '网关错误。',
  22. 503: '服务不可用,服务器暂时过载或维护。',
  23. 504: '网关超时。',
  24. };
  25. const request = async (config: any) => {
  26. const { method, params, independent, url, timeout, headers: headerInfo, ...other } = config;
  27. const { baseUrl } = Configs;
  28. const token = localStorage.getItem('token');
  29. const headers = {
  30. token,
  31. platformId: 1,
  32. ...headerInfo,
  33. };
  34. if (!/\/user\/info/.test(url)) {
  35. headers['sf-admin-token'] = localStorage.getItem('sf-admin-token');
  36. headers['yf-admin-token'] = localStorage.getItem('sf-admin-token');
  37. }
  38. // 创建axios实例
  39. const axiosIns = Axios.create();
  40. let options = {
  41. headers,
  42. baseURL: baseUrl,
  43. url,
  44. withCredentials: true,
  45. ...other,
  46. timeout: timeout || 1 * 60 * 1000,
  47. };
  48. if (method === 'post') {
  49. options = {
  50. ...options,
  51. method: 'post',
  52. data: params,
  53. };
  54. } else if (method === 'put') {
  55. options = {
  56. ...options,
  57. method: 'put',
  58. data: params,
  59. };
  60. } else {
  61. options = {
  62. ...options,
  63. method: 'get',
  64. params,
  65. };
  66. }
  67. const response = await axiosIns(options)
  68. .then((res) => {
  69. const { code, message } = res.data;
  70. // independent 存在做单独异常处理,其余走统一业务处理
  71. if (independent) return res;
  72. if (code !== '0') {
  73. notification.error({
  74. message: `请求错误 ${code}`,
  75. description: message,
  76. });
  77. if (code === '12009') {
  78. localStorage.removeItem('token');
  79. localStorage.removeItem('sf-admin-token');
  80. localStorage.removeItem('userPermission');
  81. }
  82. }
  83. return res.data;
  84. })
  85. .catch((error) => {
  86. const { response: errRes } = error;
  87. if (errRes && errRes.status) {
  88. const errorText = codeMessage[errRes.status] || errRes.statusText;
  89. const { status, url: fetchUrl } = errRes;
  90. notification.error({
  91. message: `请求错误 ${status}: ${fetchUrl}`,
  92. description: errorText,
  93. });
  94. } else if (!errRes) {
  95. notification.error({
  96. description: '您的网络发生异常,无法连接服务器',
  97. message: '网络异常',
  98. });
  99. }
  100. });
  101. return response;
  102. };
  103. export default request;

 service.ts 

  1. export const uploadFile = (params: any): Promise<any> => {
  2. const form = new FormData();
  3. form.append('files', params.file);
  4. return request({
  5. method: 'post',
  6. url: `/api/file-center/storage/upload`,
  7. body: { ...params },
  8. params: form,
  9. type: 'form',
  10. });
  11. };

form.tsx 

  1. import React, { Component } from 'react'
  2. import { Form, Row, Col, Input, Button, Select, Radio, Upload, message } from 'antd'
  3. import styles from '../../index.less'
  4. import _ from 'lodash';
  5. import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
  6. import { getStaffsList, saveBaseInfo, uploadStoreFile, getHeadStoreList, getStoreDetail } from '../../service'
  7. import { FormInstance } from 'antd/es/form';
  8. interface IState {
  9. pictureUrl: string,// 图片上传
  10. loading: boolean,
  11. }
  12. class BaseInfo extends Component<IProps, IState> {
  13. formRef = React.createRef<FormInstance>();
  14. constructor(props: IProps) {
  15. super(props);
  16. this.state = {
  17. pictureUrl: '',// 图片上传
  18. loading: false,
  19. }
  20. }
  21. beforeUpload = (file: any) => {
  22. const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  23. if (!isJpgOrPng) {
  24. message.error('请上传 JPG/JPEG/PNG 类型的文件!');
  25. }
  26. const isLt2M = file.size / 1024 < 2000;
  27. if (!isLt2M) {
  28. message.error('文件不能大于200k!');
  29. }
  30. return isJpgOrPng && isLt2M;
  31. }
  32. customRequest = (info: any) => {
  33. this.setState({ loading: true });
  34. uploadStoreFile(info).then(res => {
  35. if(res.code && res.code === '0'){
  36. console.log(res.data[0].fileUrl)
  37. this.setState({
  38. pictureUrl: res.data[0].fileUrl,
  39. loading: false
  40. })
  41. this.formRef.current!.setFieldsValue({
  42. pictureUrl: this.state.pictureUrl,
  43. })
  44. }
  45. })
  46. }
  47. render() {
  48. const uploadButton = (
  49. <div>
  50. {loading ? <LoadingOutlined /> : <PlusOutlined />}
  51. <div style={{ marginTop: 8 }}></div>
  52. </div>
  53. );
  54. return (
  55. <div>
  56. <Form>
  57. <Row>
  58. <Col span={12}>
  59. <Form.Item name="pictureUrl" label="图片上传">
  60. <Upload
  61. listType="picture-card"
  62. showUploadList={false}
  63. beforeUpload={this.beforeUpload}
  64. customRequest={this.customRequest}
  65. // onChange={this.handleChangeFile}
  66. >
  67. {pictureUrl ? <img src={pictureUrl} alt="avatar" style={{ maxWidth: '100%', maxHeight: '100%' }} /> : uploadButton}
  68. </Upload>
  69. </Form.Item>
  70. <span>图片上传(限1张,jpg,jpeg,png文件类型)</span>
  71. </Col>
  72. </Row>
  73. </Form>
  74. </div>
  75. )
  76. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/339209
推荐阅读
相关标签
  

闽ICP备14008679号