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

Take you to understand MySQL character set settings in 5 minutes

Table of contents 1. Content Overview 2. Concepts...

How to add configuration options to Discuz! Forum

Discuz! Forum has many configuration options in th...

MySQL scheduled full database backup

Table of contents 1. MySQL data backup 1.1, mysql...

How to view image information in Docker

In this article, we will need to learn how to vie...

How to upgrade CentOS7 to CentOS8 (detailed steps)

This article uses a specific example to introduce...

A simple tutorial on how to use the mysql log system

Table of contents Preface 1. Error log 2. Binary ...

MySQL whole table encryption solution keyring_file detailed explanation

illustrate MySql Community Edition supports table...

JavaScript implements the nine-grid mobile puzzle game

This article shares the specific code for JavaScr...

Web Design Summary

<br />From the birth of my first personal pa...

Example tutorial on using the sum function in MySQL

Introduction Today I will share the use of the su...

Discussion on image path issues in css (same package/different package)

In CSS files, sometimes you need to use background...

How to install docker on Linux system and log in to docker container through ssh

Note: I use Centos to install docker Step 1: Inst...

WeChat Mini Programs Implement Star Rating

This article shares the specific code for WeChat ...