您好,欢迎访问一九零五行业门户网

react怎么实现文件上传

react实现文件上传的方法:1、通过“import { table, button, modal, form, input, upload, icon, notification } from 'antd';”引入所需antd的部件;2、通过“handleok = e => {const { filelist } = this.state...}”实现提交表单并上传文件即可。
本教程操作环境:windows10系统、react18.0.0版、dell g3电脑。
react怎么实现文件上传?
react使用antd实现手动上传文件(提交表单)
前言:最近在做一个后台管理项目涉及到上传文件,使用antd里的upload实现上传文件。记录一下遇到的问题和坑。
1.要实现的效果
我要实现的效果就是点击上传文件,选择完文件后点击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视频教程》
以上就是react怎么实现文件上传的详细内容。
其它类似信息

推荐信息