{const { fileList } = this.state...}" Just submit the form and upload the file."/> {const { fileList } = this.state...}" Just submit the form and upload the file.">
search
HomeWeb Front-endFront-end Q&AHow to implement file upload in react

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
What are the limitations of React?What are the limitations of React?May 02, 2025 am 12:26 AM

React'slimitationsinclude:1)asteeplearningcurveduetoitsvastecosystem,2)SEOchallengeswithclient-siderendering,3)potentialperformanceissuesinlargeapplications,4)complexstatemanagementasappsgrow,and5)theneedtokeepupwithitsrapidevolution.Thesefactorsshou

React's Learning Curve: Challenges for New DevelopersReact's Learning Curve: Challenges for New DevelopersMay 02, 2025 am 12:24 AM

Reactischallengingforbeginnersduetoitssteeplearningcurveandparadigmshifttocomponent-basedarchitecture.1)Startwithofficialdocumentationforasolidfoundation.2)UnderstandJSXandhowtoembedJavaScriptwithinit.3)Learntousefunctionalcomponentswithhooksforstate

Generating Stable and Unique Keys for Dynamic Lists in ReactGenerating Stable and Unique Keys for Dynamic Lists in ReactMay 02, 2025 am 12:22 AM

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

JavaScript Fatigue: Staying Current with React and Its ToolsJavaScript Fatigue: Staying Current with React and Its ToolsMay 02, 2025 am 12:19 AM

JavaScriptfatigueinReactismanageablewithstrategieslikejust-in-timelearningandcuratedinformationsources.1)Learnwhatyouneedwhenyouneedit,focusingonprojectrelevance.2)FollowkeyblogsliketheofficialReactblogandengagewithcommunitieslikeReactifluxonDiscordt

Testing Components That Use the useState() HookTesting Components That Use the useState() HookMay 02, 2025 am 12:13 AM

TotestReactcomponentsusingtheuseStatehook,useJestandReactTestingLibrarytosimulateinteractionsandverifystatechangesintheUI.1)Renderthecomponentandcheckinitialstate.2)Simulateuserinteractionslikeclicksorformsubmissions.3)Verifytheupdatedstatereflectsin

Keys in React: A Deep Dive into Performance Optimization TechniquesKeys in React: A Deep Dive into Performance Optimization TechniquesMay 01, 2025 am 12:25 AM

KeysinReactarecrucialforoptimizingperformancebyaidinginefficientlistupdates.1)Usekeystoidentifyandtracklistelements.2)Avoidusingarrayindicesaskeystopreventperformanceissues.3)Choosestableidentifierslikeitem.idtomaintaincomponentstateandimproveperform

What are keys in React?What are keys in React?May 01, 2025 am 12:25 AM

Reactkeysareuniqueidentifiersusedwhenrenderingliststoimprovereconciliationefficiency.1)TheyhelpReacttrackchangesinlistitems,2)usingstableanduniqueidentifierslikeitemIDsisrecommended,3)avoidusingarrayindicesaskeystopreventissueswithreordering,and4)ens

The Importance of Unique Keys in React: Avoiding Common PitfallsThe Importance of Unique Keys in React: Avoiding Common PitfallsMay 01, 2025 am 12:19 AM

UniquekeysarecrucialinReactforoptimizingrenderingandmaintainingcomponentstateintegrity.1)Useanaturaluniqueidentifierfromyourdataifavailable.2)Ifnonaturalidentifierexists,generateauniquekeyusingalibrarylikeuuid.3)Avoidusingarrayindicesaskeys,especiall

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.