{const { fileList } = this.state...}" Just submit the form and upload the file."/> {const { fileList } = this.state...}" Just submit the form and upload the file.">

Home  >  Article  >  Web Front-end  >  How to implement file upload in react

How to implement file upload in react

藏色散人
藏色散人Original
2023-01-06 15:54:063421browse

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

How to implement file upload in react

The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.

How to upload files in react?

react uses antd to implement manual file upload (submit form)

Foreword: Recently I am working on a background management project that involves uploading files, using antd in Upload implements uploading files. Record the problems and pitfalls encountered.

1. The effect to be achieved

How to implement file upload in react

The effect I want to achieve is to click to upload the file, and click ok after selecting the file (that is, after submitting the form, Upload) is actually uploading files manually. Let me introduce my approach and some pitfalls I encountered.

2. Implementation steps

1.Introduce the required antd components

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

This is the form

 <Modal
          title="文件上传"
          visible={this.state.visible}
          onOk={this.handleOk} //点击按钮提价表单并上传文件
          onCancel={this.handleCancel}
        >
          <Form layout="vertical" onSubmit={this.handleSubmit}>
            <Form.Item>
              <div  key={Math.random()}>//点击关闭在次打开还会有上次上传文件的缓存
                <Upload {...props}>
                  <Button type="primary">
                    <Icon type="upload" />选择文件
                 </Button>
                </Upload>
 
              </div>
            </Form.Item>
            <Form.Item label="文件名(可更改)">
              {getFieldDecorator(&#39;filename&#39;, {
                // initialValue:this.state.defEmail,
                rules: [
                  {
                    message: &#39;请输入正确的文件名&#39;,
                    // pattern: /^[0-9]+$/,
                  },
                  {
                    required: true,
                    message: &#39;请输入文件名&#39;,
                  },
                ],
              })(<Input />)}
            </Form.Item>
            <Form.Item label="描述(选填)">
              {getFieldDecorator(&#39;describe&#39;, {
 
                rules: [
                  {
                    message: &#39;描述不能为空&#39;,
                  },
                  {
                    required: false,
                    message: &#39;请输入描述&#39;,
                  },
                ],
              })(<TextArea />)}
            </Form.Item>
            <Form.Item label="文件类型">
              {getFieldDecorator(&#39;filetype&#39;, {
                rules: [
                  {
                    message: &#39;文件类型&#39;,
                  },
                  {
                    required: true,
                    message: &#39;文件类型&#39;,
                  },
                ],
              })(<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(&#39;.&#39;) + 1);//截取文件后缀名
        this.props.form.setFieldsValue({ &#39;filename&#39;: name, &#39;filetype&#39;: fileExtension });//选择完文件后把文件名和后缀名自动填入表单
        this.setState(state => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      fileList,
    };

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

handleOk = e => {//点击ok确认上传
    const { fileList } = this.state;
    let formData = new FormData();
    fileList.forEach(file => {
      formData.append(&#39;file&#39;, file);
    });
 
    this.props.form.validateFields((err, values) => { //获取表单值
      let { filename, filetype, describe } = values;
      formData.append(&#39;name&#39;, filename);
      formData.append(&#39;type&#39;, filetype);
      formData.append("dir", "1");
      if(describe==undefined){
        formData.append(&#39;description&#39;,"");
      }else{
        formData.append(&#39;description&#39;,describe);
      }
      
      UploadFile(formData).then(res => { //这个是请求
        if (res.status == 200 && res.data != undefined) {
          notification.success({
            message: "上传成功",
            description: res.data,
          });
        } else {
          notification.error({
            message: "上传失败",
            description: res.status,
          });
        }
      })
      this.setState({
        visible: false
      });
 
    })
  };

Note that I use axios, post must use formData.append ("Interface parameter name", "Value to be passed"); if you don't want to Using axios, you can also use other requests

fetch(url, { //fetch请求
        method: &#39;POST&#39;,
        body: formData,
    })
 
 
 
 
 
 
      axios({ //axios
        method: &#39;post&#39;,
        url: url,
        data: formData,
        headers:{ //可加可不加
          &#39;Content-Type&#39;: &#39;multipart/form-data; boundary=---- 
           WebKitFormBoundary6jwpHyBuz5iALV7b&#39;
        }
    })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });

so that you can upload files manually.

3. Pitfalls

After selecting the file for the first time, click Upload. When I opened the Model for the second time, I found that the file list from the last time was still there. The method I found online was to give upload and a key value, but the cache will disappear only after clicking ok and opening the Model for the second time, but it will still exist when I click canel.

<div key={Math.random()}>
                <Upload  {...props}>
                  <Button type="primary">
                    <Icon type="upload" />选择文件
                 </Button>
                </Upload>
 
              </div>

The best way is this.setState to empty the file list in the state

 this.props.form.resetFields()//添加之前把input值清空
    this.setState({
      visible: true,
      fileList: [] //把文件列表清空
    });

You can also add a destroyOnClose attribute to Modal to destroy the child elements in Modal when closing

Recommended learning: "react video tutorial"

The above is the detailed content of How to implement file upload in react. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn