reactjs 在react js中使用ant design上传图像

bihw5rsg  于 2023-03-01  发布在  React
关注(0)|答案(3)|浏览(239)

我有一个简单的应用程序,用户应该上传它的图像。上传图像后,点击get data from upload按钮,用户应该看到console.log("Received values of form: ", values);的结果现在,结果出现,但在一个项目数组的形式。
我想实现的是,得到最后上传的图像,在同一时间在前端我想看到只有一个正方形的图像,但现在如果我上传3张图像,我得到3个正方形。
ps:对我来说,保存后必须得到thumbUrl。有图像的base64数据。

import React, { useState } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import {
  Form,
  Select,
  InputNumber,
  Switch,
  Radio,
  Slider,
  Button,
  Upload,
  Rate,
  Checkbox,
  Row,
  Col
} from "antd";
import { UploadOutlined, InboxOutlined } from "@ant-design/icons";

const { Option } = Select;
const formItemLayout = {
  labelCol: {
    span: 6
  },
  wrapperCol: {
    span: 14
  }
};

const normFile = (e) => {
  console.log("Upload event:", e);

  if (Array.isArray(e)) {
    return e;
  }

  return e && e.fileList;
};

const Demo = () => {
  const onFinish = (values) => {
    console.log("Received values of form: ", values);
  };
  const [state, setState] = useState({
    loading: false
  });

  function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener("load", () => callback(reader.result));
    reader.readAsDataURL(img);
  }
  const handleChange = (info) => {
    let fileList = [...info.fileList];

    if (info.file.status === "uploading") {
      setState({ loading: true });
      return;
    }
    if (info.file.status === "done") {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (imageUrl) =>
        setState({
          imageUrl,
          loading: false
        })
      );
    }
  };

  function beforeUpload(file) {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      console.error("You can only upload JPG/PNG file!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      console.error("Image must smaller than 2MB!");
    }
    return isJpgOrPng && isLt2M;
  }

  const uploadButton = (
    <div>
      <div className="ant-upload-text">Upload img</div>
    </div>
  );
  const { imageUrl } = state;
  return (
    <Form
      name="validate_other"
      {...formItemLayout}
      onFinish={onFinish}
      initialValues={{
        "input-number": 3,
        "checkbox-group": ["A", "B"],
        rate: 3.5
      }}
    >
      <Form.Item
        name="upload"
        label="Upload"
        valuePropName="fileList"
        getValueFromEvent={normFile}
      >
        <Upload
          listType="picture-card"
          className="avatar-uploader"
          showUploadList={true}
          action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
          beforeUpload={beforeUpload}
          onChange={handleChange}
        >
          {imageUrl ? (
            <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
          ) : (
            uploadButton
          )}
        </Upload>
      </Form.Item>

      <Form.Item
        wrapperCol={{
          span: 12,
          offset: 6
        }}
      >
        <Button type="primary" htmlType="submit">
          get data from upload
        </Button>
      </Form.Item>
    </Form>
  );
};

ReactDOM.render(<Demo />, document.getElementById("container"));

问:如何达到我上面所描述的?
演示:https://codesandbox.io/s/currying-pine-hq412?file=/index.js:0-2985

iklwldmw

iklwldmw1#

您可以通过配置fileList来获得对上传文件的完全控制权(请参见文件列表的Antd Upload API)。
文件列表
已上载(受控)文件的列表。
文档中也提供了如何使用fileList并减小列表大小的演示。
注:使用fileList时可能会出现一些问题,请参阅this(#2423) ant github issue了解详细信息。

djmepvbi

djmepvbi2#

您只需通过getValueFromEvent通知窗体获取fileList数组中的最后一项

const normFile = (e) => {
  console.log("Upload event:", e);

  if (Array.isArray(e)) {
    return e;
  }

  //change "return e && e.fileList" for
  return e && e.fileList.slice(-1);
};
kcwpcxri

kcwpcxri3#

import { PlusOutlined,LoadingOutlined} from '@ant-design/icons';
import { message, Upload } from 'antd';
import { useState } from 'react';
**//download - npm i antd-img-crop**
import ImgCrop from 'antd-img-crop';

const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
};
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'||file.url ===  getBase64(file);
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};
const AvatarChanger = () => {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState();
  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
    }
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload
      </div>
    </div>
  );
  return (
    <>
      <ImgCrop>
      <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
        beforeUpload={beforeUpload}
        onChange={handleChange}
      >
        {imageUrl ? (
          <img
            src={imageUrl}
            alt="avatar"
            style={{
              width: '100%',
            }}
          />
        ) : (
          uploadButton
        )}
      </Upload>
      </ImgCrop>
    </>
  );
};
export default AvatarChanger;

相关问题