300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > react使用antd实现手动上传文件(提交表单)

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

时间:2022-03-31 00:24:05

相关推荐

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

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

1.要实现的效果

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

2.实现步骤

1.引入所需antd的部件

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

这个时表单的

<Modaltitle="文件上传"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,只需要把beforeUpload返回false后,手动上传文件。

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({ //axiosmethod: '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);});

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

antd 3.x官网示例:

上传 Upload - Ant Design-手动上传

antd 4.x 官网示例:

上传 Upload - Ant Design-手动上传

antd 5.x官网示例:

上传 Upload - Ant Design-手动上传

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 里的子元素

upload用法可参考antd官网

antd v4 -手动上传 官网示例

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。