IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> JavaScript知识库 -> 【React】antd上传文件组件customRequest自定义上传实现 -> 正文阅读

[JavaScript知识库]【React】antd上传文件组件customRequest自定义上传实现

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>
    )

}

  JavaScript知识库 最新文章
ES6的相关知识点
react 函数式组件 & react其他一些总结
Vue基础超详细
前端JS也可以连点成线(Vue中运用 AntVG6)
Vue事件处理的基本使用
Vue后台项目的记录 (一)
前后端分离vue跨域,devServer配置proxy代理
TypeScript
初识vuex
vue项目安装包指令收集
上一篇文章      下一篇文章      查看所有文章
加:2021-10-27 12:44:50  更:2021-10-27 12:47:15 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年4日历 -2024/4/19 19:02:36-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码