站长资讯网
最全最丰富的资讯网站

react怎么实现文件上传

react实现文件上传的方法:1、通过“import { Table, Button, Modal, Form, Input, Upload, Icon, notification } from 'antd';”引入所需antd的部件;2、通过“handleOk = e => {const { fileList } = this.state…}”实现提交表单并上传文件即可。

react怎么实现文件上传

本教程操作环境:Windows10系统、react18.0.0版、Dell G3电脑。

react怎么实现文件上传?

react使用antd实现手动上传文件(提交表单)

前言:最近在做一个后台管理项目涉及到上传文件,使用antd里的Upload实现上传文件。记录一下遇到的问题和坑。

1.要实现的效果

react怎么实现文件上传

我要实现的效果就是点击上传文件,选择完文件后点击ok(也就是提交表单后在上传)其实就是手动上传文件。下面我来介绍一下我的做法和我遇到的一些坑。

2.实现步骤

1.引入所需antd的部件

import { Table, Button, Modal, Form, Input, Upload, Icon, notification } from 'antd';
登录后复制

这个是表单的

 <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('filename', {                 // initialValue:this.state.defEmail,                 rules: [                   {                     message: '请输入正确的文件名',                     // pattern: /^[0-9]+$/,                   },                   {                     required: true,                     message: '请输入文件名',                   },                 ],               })(<Input />)}             </Form.Item>             <Form.Item label="描述(选填)">               {getFieldDecorator('describe', {                   rules: [                   {                     message: '描述不能为空',                   },                   {                     required: false,                     message: '请输入描述',                   },                 ],               })(<TextArea />)}             </Form.Item>             <Form.Item label="文件类型">               {getFieldDecorator('filetype', {                 rules: [                   {                     message: '文件类型',                   },                   {                     required: true,                     message: '文件类型',                   },                 ],               })(<Input disabled={true} />)}             </Form.Item>           </Form>         </Modal>
登录后复制

下面的代码是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 });//选择完文件后把文件名和后缀名自动填入表单         this.setState(state => ({           fileList: [...state.fileList, file],         }));         return false;       },       fileList,     };
登录后复制

下面是重点提交表单并上传文件

handleOk = e => {//点击ok确认上传     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: "上传成功",             description: res.data,           });         } else {           notification.error({             message: "上传失败",             description: res.status,           });         }       })       this.setState({         visible: false       });       })   };
登录后复制

注意我用的axios,post必须使用formData.append("接口参数名",“要传的值”);如果不想用axios还可以用别的请求

fetch(url, { //fetch请求         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);     });
登录后复制

这样就能实现手动上传文件了。

3.遇到的坑

第一次选择完文件,点击上传。第二次在打开Model发现上回的文件列表还在,我在网上找的方法是给upload及一个key值但只有点击ok后第二次打开Model缓存才会消失,但是点击canel还会存在。

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

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

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

也可以给Modal加一个 destroyOnClose 属性 关闭时销毁 Modal 里的子元素

推荐学习:《react视频教程》

赞(0)
分享到: 更多 (0)