React uses antd's upload component to implement the file form submission function (complete code)

React uses antd's upload component to implement the file form submission function (complete code)

I have just started using react to do projects, and I am very unskilled and a complete novice. Newbies can read it because what I write is very simple and straightforward.

The project needs to implement the submission of attachments in the form, and the uploaded files are not saved separately and the interface is called.

import { Form, Button, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
  
  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);
    };
  
    return (
      <Form
        name="validate_other"
        onFinish={onFinish}
        initialValues={{
          'input-number': 3,
          'checkbox-group': ['A', 'B'],
          rate: 3.5,
        }}
      >
        <Form.Item
          name="upload"
          label="Upload"
          valuePropName="fileList"
          getValueFromEvent={normFile}
        >
          <Upload name="logo" action="/upload.do" listType="picture">
            <Button icon={<UploadOutlined />}>Click to upload</Button>
          </Upload>
        </Form.Item>
      </Form>
    );
  };
  
  ReactDOM.render(<Demo />, mountNode);

Here is a form that contains a file upload function. (In fact, the code here is an example from Antd's official documentation. I only deleted the redundant parts and left the rest as is).

The following is an explanation.

First of all, we need to think about how to prevent files from being uploaded automatically. The antd document gives a method called beforeUpload. When the beforeUpload method returns false, the file upload will be stopped.

The above will stop the automatic uploading of files. Next, we consider how to obtain the uploaded file and store it in the parameters passed to the backend.

This part of the code is the upload code method, because we need to upload the file and submit it together with the form. So we make some modifications in this method and store the file in the formData object. Here we first explain the formData object, which is mainly used to transfer files to the backend.

First create a new formData object, and then append the file into it, so that the uploaded file is already stored in formData.

Other data in the form can also be stored in formData in the same way, and formData can be passed to the backend.

There is another issue that needs attention at this time.

fetch(url, {

        //fetch request method: 'POST',

        body: formData,

})

or

 axios({ //axios
        method: 'post',
        url: url,
        data: formData,
    })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });

It must be set to successfully pass parameters, otherwise the parameters will not be successfully passed when calling the interface.

What does it look like to successfully carry parameters? You can click F12 on the relevant page to view, network, there will be a Form Data column at the bottom, which will display all the parameters passed.

The final code is as follows:

import { Form, Button, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
  
  const normFile = (e) => {
    console.log('Upload event:', e);
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };
  const beforeUpload = ({fileList}) => {
      return false;
  }
  const Demo = () => {
    const onFinish = (values) => {
      console.log('Received values ​​of form: ', values);
    };
  
    return (
      <Form
        name="validate_other"
        onFinish={onFinish}
        initialValues={{
          'input-number': 3,
          'checkbox-group': ['A', 'B'],
          rate: 3.5,
        }}
      >
        <Form.Item
          name="upload"
          label="Upload"
          valuePropName="fileList"
          getValueFromEvent={normFile}
        >
          <Upload name="logo"  
            beforeUpload={beforeUpload}
          >
            <Button icon={<UploadOutlined />}>Click to upload</Button>
          </Upload>
        </Form.Item>
      </Form>
    );
  };
  
  ReactDOM.render(<Demo />, mountNode);

This is the end of this article about using antd's upload component in react to submit files together with the form. For more relevant react implementation of file form submission content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Solution to React pure function component setState not refreshing the page update
  • React implements dynamic pop-up window component
  • Implementation of React star rating component
  • How to make React components full screen

<<:  Summary of new usage of vi (vim) under Linux

>>:  MySQL 8.0.11 installation tutorial with pictures and text

Recommend

Centos7.5 configuration java environment installation tomcat explanation

Tomcat is a web server software based on Java lan...

npm Taobao mirror modification explanation

1. Top-level usage 1. Install cnpm npm i -g cnpm ...

Hadoop 2.x vs 3.x 22-point comparison, Hadoop 3.x improvements over 2.x

Question Guide 1. How does Hadoop 3.x tolerate fa...

Application of anchor points in HTML

Set Anchor Point <a name="top"><...

VMware Workstation 14 Pro installation Ubuntu 16.04 tutorial

This article records the specific method of insta...

MySQL query redundant indexes and unused index operations

MySQL 5.7 and above versions provide direct query...

How to solve the error "ERROR 1045 (28000)" when logging in to MySQL

Today, I logged into the server and prepared to m...

A brief summary of vue keep-alive

1. Function Mainly used to preserve component sta...

How to restore data using binlog in mysql5.7

Step 1: Ensure that MySQL has binlog enabled show...

Solution to overflow:hidden failure in CSS

Cause of failure Today, when I was writing a caro...

Implementation code for partial refresh of HTML page

Event response refresh: refresh only when request...

A simple method to merge and remove duplicate MySQL tables

Scenario: The crawled data generates a data table...

A small question about the execution order of SQL in MySQL

I encountered a sql problem at work today, about ...

MySQL derived table (Derived Table) simple usage example analysis

This article uses an example to describe the simp...