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

request.ts

/*
 * @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>
    )

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React Antd提供了一个Draggable组件,可以实现拖拽组件的功能。 首先,需要安装antd组件库和react-dnd库: ```bash npm install antd react-dnd react-dnd-html5-backend ``` 然后,在组件中引入Draggable组件和DragDropContext组件: ```jsx import { Draggable } from 'react-drag-and-drop'; import { DragDropContext } from 'react-dnd'; import HTML5Backend from 'react-dnd-html5-backend'; import { Card } from 'antd'; const DragCard = ({ id, text, index, moveCard }) => { const style = { marginBottom: 16, }; return ( <Draggable key={id} draggableId={id} index={index} onDragEnd={(result) => moveCard(result.source.index, result.destination?.index)} > {(provided) => ( <Card {...provided.draggableProps} {...provided.dragHandleProps} ref={provided.innerRef} style={{ ...provided.draggableProps.style, ...style }} > {text} </Card> )} </Draggable> ); }; const DragList = ({ cards, moveCard }) => { return ( <div> {cards.map((card, index) => ( <DragCard key={card.id} index={index} {...card} moveCard={moveCard} /> ))} </div> ); }; const App = () => { const [cards, setCards] = useState([ { id: 'card-1', text: 'Card 1' }, { id: 'card-2', text: 'Card 2' }, { id: 'card-3', text: 'Card 3' }, ]); const moveCard = useCallback((sourceIndex, destinationIndex) => { if (destinationIndex === undefined) { return; } const newCards = [...cards]; const [removed] = newCards.splice(sourceIndex, 1); newCards.splice(destinationIndex, 0, removed); setCards(newCards); }, [cards]); return ( <DragDropContext backend={HTML5Backend}> <DragList cards={cards} moveCard={moveCard} /> </DragDropContext> ); }; ``` 在上述代码中,Draggable组件用于包裹需要拖拽的组件,而DragDropContext组件用于提供拖拽功能的上下文。通过onDragEnd回调函数,可以获取到拖拽的源位置和目标位置,然后更新数据源的位置。在拖拽的过程中,可以通过provided参数传递组件的属性,如样式等。 最后,将DragList组件渲染到页面中即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值