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

MySQL DATE_ADD and ADDDATE functions add a specified time interval to a date

MySQL DATE_ADD(date,INTERVAL expr type) and ADDDA...

Example of implementing todo application with Vue

background First of all, I would like to state th...

How to operate MySql database with gorm

1. Setting case sensitivity of fields in the tabl...

What you need to know about responsive design

Responsive design is to perform corresponding ope...

Canvas draws scratch card effect

This article shares the specific code for drawing...

CSS controls the spacing between words through the letter-spacing property

letter-spacing property : Increase or decrease th...

How to implement Mysql scheduled tasks under Linux

Assumption: The stored procedure is executed ever...

HTML Nine-grid Layout Implementation Method

Diversifying website layouts is our front-end spe...

Detailed explanation of common usage of MySQL query conditions

This article uses examples to illustrate the comm...

Writing a rock-paper-scissors game in JavaScript

This article shares the specific code for writing...

How to implement scheduled backup of MySQL database

1. Create a shell script vim backupdb.sh Create t...

A useful mobile scrolling plugin BetterScroll

Table of contents Make scrolling smoother BetterS...

How to set up vscode remote connection to server docker container

Table of contents Pull the image Run the image (g...

HTML page jump code

Save the following code as the default homepage fi...