How react implements file upload

01-29-2023

This article introduces the relevant knowledge of how react implements file upload. During the operation of the actual case, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. ! I hope you read it carefully and learn something!

The method of react to realize file upload: 1. Through import { Table, Button, Modal, Form, Input, Upload, Icon, notification } from 'antd'; Introduce the required antd components; 2. Submit the form and upload the file through handleOk = e => {const { fileList } = this.state...}.

react uses antd to upload files manually (submit form)

1. The effect to be achieved

2. Implementation steps

1. Import required antd components

import { Table, Button, Modal, Form, Input, Upload, Icon, notification } from 'antd';

This is the form

<Modal          title="File upload"          visible={this.state.visible}          onOk={this.handleOk} //Click the button to raise the price form and upload the file
          onCancel={this.handleCancel}        >          <Form layout="vertical" onSubmit={this.handleSubmit}>            <Form.Item>              <div  key={Math.random()}>//Click Close to open the cache of the last uploaded file
                <Upload {...props}>                  <Button type="primary">                    <Icon type="upload" />Select File
                 </Button>                </Upload> 
              </div>            </Form.Item>            <Form.Item label="File name (changeable)">              {getFieldDecorator('filename', {
                // initialValue:this.state.defEmail,
                rules: [
                  {
                    message: 'Please enter the correct file name',
                    // pattern: /^[0-9]+$/,
                  },
                  {
                    required: true,
                    message: 'Please enter a file name',
                  },
                ],
              })(<Input />)}
            </Form.Item>            <Form.Item label="Description (optional)">              {getFieldDecorator('describe', {
 
                rules: [
                  {
                    message: 'Description cannot be empty',
                  },
                  {
                    required: false,
                    message: 'Please enter a description',
                  },
                ],
              })(<TextArea />)}
            </Form.Item>            <Form.Item label="file type">              {getFieldDecorator('filetype', {
                rules: [
                  {
                    message: 'file type',
                  },
                  {
                    required: true,
                    message: 'file type',
                  },
                ],
              })(<Input disabled={true} />)}
            </Form.Item>          </Form>        </Modal>

The following code is the props of Upload

  const props = {
      showUploadList: true,
      onRemove: file => {
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: file => {
        console.log(file)
        let { name } = file;
        var fileExtension = name.substring(name.lastIndexOf('.') + 1);//Intercept file suffix name       this.props.form.setFieldsValue({ 'filename': name, 'filetype': fileExtension });//Automatically fill the file name and suffix name in the form after selecting the file        this.setState(state => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      fileList,
    };

The following is the focus on submitting the form and uploading the file

handleOk = e => {//Click OK to confirm the upload    const { fileList } = this.state;
    let formData = new FormData();
    fileList.forEach(file => {
      formData.append('file', file);
    });
 
    this.props.form.validateFields((err, values) => {      let { filename, filetype, describe } = values;
      formData.append('name', filename);
      formData.append('type', filetype);
      formData.append("dir", "1");
      if(describe==undefined){
        formData.append('description',"");
      }else{
        formData.append('description',describe);
      }
      
      UploadFile(formData).then(res => {      if (res.status == 200 && res.data != undefined) {
          notification.success({
            message: "Upload succeeded",
            description: res.data,
          });
        } else {
          notification.error({
            message: "Upload failed",
            description: res.status,
          });
        }
      })
      this.setState({
        visible: false      });
 
    })
  };

Note that I use axios, post must use formData.append ("interface parameter name", the value to be passed); if you don't want to use axios, you can use other request

fetch(url, { //Fetch request        method: 'POST',
        body: formData,
    })
 
 
 
 
 
 
      axios({ //axios        method: 'post',
        url: url,
        data: formData,
        headers:{ //Can be added or not       'Content-Type': 'multipart/form-data; boundary=---- 
           WebKitFormBoundary6jwpHyBuz5iALV7b'        }
    })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });

In this way, you can upload files manually.


Copyright Description:No reproduction without permission。

Knowledge sharing community for developers。

Let more developers benefit from it。

Help developers share knowledge through the Internet。

Follow us