简体   繁体   中英

Upload an image using ant design in react js

I have a simple application where user should upload its image. After uploading the image, and clicking on get data from upload button, the user should see the result in console.log("Received values of form: ", values); Now, the result appears but in form of an array of items.
What i want to achieve is, to get just the last uploaded image there, and in the same time on front end i want to see just one square with image, but now if i upload 3 images, i get 3 squares.
ps: for me is obligatory to get the thumbUrl after saving. There is base64 data of image.

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

Question: How to achieve what i described above?
demo: https://codesandbox.io/s/currying-pine-hq412?file=/index.js:0-2985

You can gain full control over the uploaded files by configuring fileList (see Antd Upload Api for fileList).

fileList
List of files that have been uploaded (controlled).

A demo how to use the fileList and reduce the list size is provided in the docs too.

Note: There might be some issues while using fileList , see this(#2423) ant github issue for details.

You just need to notify the form to get the last item in the fileList array, through getValueFromEvent

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM