欧美亚洲中文,在线国自产视频,欧洲一区在线观看视频,亚洲综合中文字幕在线观看

      1. <dfn id="rfwes"></dfn>
          <object id="rfwes"></object>
        1. 站長(zhǎng)資訊網(wǎng)
          最全最豐富的資訊網(wǎng)站

          react怎么實(shí)現(xiàn)文件上傳

          react實(shí)現(xiàn)文件上傳的方法:1、通過(guò)“import { Table, Button, Modal, Form, Input, Upload, Icon, notification } from 'antd';”引入所需antd的部件;2、通過(guò)“handleOk = e => {const { fileList } = this.state…}”實(shí)現(xiàn)提交表單并上傳文件即可。

          react怎么實(shí)現(xiàn)文件上傳

          本教程操作環(huán)境:Windows10系統(tǒng)、react18.0.0版、Dell G3電腦。

          react怎么實(shí)現(xiàn)文件上傳?

          react使用antd實(shí)現(xiàn)手動(dòng)上傳文件(提交表單)

          前言:最近在做一個(gè)后臺(tái)管理項(xiàng)目涉及到上傳文件,使用antd里的Upload實(shí)現(xiàn)上傳文件。記錄一下遇到的問(wèn)題和坑。

          1.要實(shí)現(xiàn)的效果

          react怎么實(shí)現(xiàn)文件上傳

          我要實(shí)現(xiàn)的效果就是點(diǎn)擊上傳文件,選擇完文件后點(diǎn)擊ok(也就是提交表單后在上傳)其實(shí)就是手動(dòng)上傳文件。下面我來(lái)介紹一下我的做法和我遇到的一些坑。

          2.實(shí)現(xiàn)步驟

          1.引入所需antd的部件

          import { Table, Button, Modal, Form, Input, Upload, Icon, notification } from 'antd';
          登錄后復(fù)制

          這個(gè)是表單的

           <Modal           title="文件上傳"           visible={this.state.visible}           onOk={this.handleOk} //點(diǎn)擊按鈕提價(jià)表單并上傳文件           onCancel={this.handleCancel}         >           <Form layout="vertical" onSubmit={this.handleSubmit}>             <Form.Item>               <div  key={Math.random()}>//點(diǎn)擊關(guān)閉在次打開(kāi)還會(huì)有上次上傳文件的緩存                 <Upload {...props}>                   <Button type="primary">                     <Icon type="upload" />選擇文件                  </Button>                 </Upload>                 </div>             </Form.Item>             <Form.Item label="文件名(可更改)">               {getFieldDecorator('filename', {                 // initialValue:this.state.defEmail,                 rules: [                   {                     message: '請(qǐng)輸入正確的文件名',                     // pattern: /^[0-9]+$/,                   },                   {                     required: true,                     message: '請(qǐng)輸入文件名',                   },                 ],               })(<Input />)}             </Form.Item>             <Form.Item label="描述(選填)">               {getFieldDecorator('describe', {                   rules: [                   {                     message: '描述不能為空',                   },                   {                     required: false,                     message: '請(qǐng)輸入描述',                   },                 ],               })(<TextArea />)}             </Form.Item>             <Form.Item label="文件類型">               {getFieldDecorator('filetype', {                 rules: [                   {                     message: '文件類型',                   },                   {                     required: true,                     message: '文件類型',                   },                 ],               })(<Input disabled={true} />)}             </Form.Item>           </Form>         </Modal>
          登錄后復(fù)制

          下面的代碼是Upload的props

            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);//截取文件后綴名         this.props.form.setFieldsValue({ 'filename': name, 'filetype': fileExtension });//選擇完文件后把文件名和后綴名自動(dòng)填入表單         this.setState(state => ({           fileList: [...state.fileList, file],         }));         return false;       },       fileList,     };
          登錄后復(fù)制

          下面是重點(diǎn)提交表單并上傳文件

          handleOk = e => {//點(diǎn)擊ok確認(rèn)上傳     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 => { //這個(gè)是請(qǐng)求         if (res.status == 200 && res.data != undefined) {           notification.success({             message: "上傳成功",             description: res.data,           });         } else {           notification.error({             message: "上傳失敗",             description: res.status,           });         }       })       this.setState({         visible: false       });       })   };
          登錄后復(fù)制

          注意我用的axios,post必須使用formData.append("接口參數(shù)名",“要傳的值”);如果不想用axios還可以用別的請(qǐng)求

          fetch(url, { //fetch請(qǐng)求         method: 'POST',         body: formData,     })                   axios({ //axios         method: 'post',         url: url,         data: formData,         headers:{ //可加可不加           'Content-Type': 'multipart/form-data; boundary=----             WebKitFormBoundary6jwpHyBuz5iALV7b'         }     })     .then(function (response) {         console.log(response);     })     .catch(function (error) {         console.log(error);     });
          登錄后復(fù)制

          這樣就能實(shí)現(xiàn)手動(dòng)上傳文件了。

          3.遇到的坑

          第一次選擇完文件,點(diǎn)擊上傳。第二次在打開(kāi)Model發(fā)現(xiàn)上回的文件列表還在,我在網(wǎng)上找的方法是給upload及一個(gè)key值但只有點(diǎn)擊ok后第二次打開(kāi)Model緩存才會(huì)消失,但是點(diǎn)擊canel還會(huì)存在。

          <div key={Math.random()}>                 <Upload  {...props}>                   <Button type="primary">                     <Icon type="upload" />選擇文件                  </Button>                 </Upload>                 </div>
          登錄后復(fù)制

          最好的方法就是this.setState把state里文件列表置空

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

          也可以給Modal加一個(gè) destroyOnClose 屬性 關(guān)閉時(shí)銷毀 Modal 里的子元素

          推薦學(xué)習(xí):《react視頻教程》

          贊(0)
          分享到: 更多 (0)
          網(wǎng)站地圖   滬ICP備18035694號(hào)-2    滬公網(wǎng)安備31011702889846號(hào)