Bootstrap

react中使用Ant Design的Upload 组件,使用后端提供的接口上传图片,不使用默认的action 请求

1、上传单张图片

import { UploadOutlined } from "@ant-design/icons";
import { Button, message, Upload } from "antd";
import { uploadImagwe } from "../../api/api";

const Home = () => {
  const props = {
    beforeUpload: () => {
      return false;
    },
    onChange: (info) => {
      const formData = new FormData();
      const fileList = info.fileList;
      fileList.forEach((file) => {
        formData.append("name", file.originFileObj);
      });
      // 调后端接口发送上传的图片
      uploadImagwe(formData).then((res) => {
        if (res.code === 0) {
          message.success("upload successfully.");
        } else {
          message.error("upload failed.");
        }
      });
    },
    multiple: true,
  };
  return (
    <Upload {...props}>
      <Button icon={<UploadOutlined />}>Select File</Button>
    </Upload>
  );
};
export default Home;

2、上传多张图片(可拖拽和点击)

import React from "react";
import { CloudUploadOutlined } from "@ant-design/icons";
import { message, Upload } from "antd";
import { uploadImage } from "../../../api/api";
import styles from "./UploadArea.module.scss";

function UploadArea(props) {
  const { Dragger } = Upload;
  const draggerProps = {
    name: "file",
    multiple: true,
    accept: "image/png, image/jpg, image/jpeg, image/gif",
    beforeUpload: () => {
      return false;
    },
    onChange(info) {
      const fileList = info.fileList;
      const formData = new FormData();
      fileList.forEach((file) => {
        formData.append("name", file.originFileObj);
      });
      // 调后端接口发送上传的图片
      uploadImage(formData).then((res) => {
        if (res.code === 0) {
          message.success("图片上传成功");
        } else {
          message.error(res.message);
        }
      });
    },
  };
  return (
    <div className={styles.uploadContainer}>
      {/* 图片上传 */}
      <Dragger {...draggerProps}>
        <p className="ant-upload-drag-icon">
          <CloudUploadOutlined />
        </p>
        <p className="ant-upload-text">单击或拖动图片到此区域识别</p>
        <p className="ant-upload-hint">支持单次或批量上传</p>
      </Dragger>
    </div>
  );
}

export default UploadArea;

3、使用默认的action示例如下(如上传一张新头像之后替换之前的旧头像):

	  const [avatar, setAvatar] = useState('');  // 头像地址
	  
      <div style={{ fontWeight: 100, height: 50 }}>当前头像:</div>
      <Image src={avatar} width={100} />
      <div style={{ fontWeight: 100, height: 50 }}>上传新头像:</div>
      <Upload
        action="/api/upload"
        listType="picture-card"
        maxCount={1}
        onChange={(e) => {
          if (e.file.status === "done") {
            // 说明上传已经完成
            const url = e.file.response.data;
            setAvatar(url)
          }
        }}
      >
        <PlusOutlined />
      </Upload>

下方是我微信公众号的二维码,关于react及其他相关知识点会在公众号上面更新,可以扫码关注以下,有什么问题也可以通过公众号跟我留言哦
在这里插入图片描述

;