react實現(xiàn)文件上傳的方法:1、通過“import { Table, Button, Modal, Form, Input, Upload, Icon, notification } from 'antd';”引入所需antd的部件;2、通過“handleOk = e => {const { fileList } = this.state…}”實現(xiàn)提交表單并上傳文件即可。
本教程操作環(huán)境:Windows10系統(tǒng)、react18.0.0版、Dell G3電腦。
react怎么實現(xiàn)文件上傳?
react使用antd實現(xiàn)手動上傳文件(提交表單)
前言:最近在做一個后臺管理項目涉及到上傳文件,使用antd里的Upload實現(xiàn)上傳文件。記錄一下遇到的問題和坑。
1.要實現(xiàn)的效果
我要實現(xiàn)的效果就是點擊上傳文件,選擇完文件后點擊ok(也就是提交表單后在上傳)其實就是手動上傳文件。下面我來介紹一下我的做法和我遇到的一些坑。
2.實現(xiàn)步驟
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("接口參數(shù)名",“要傳的值”);如果不想用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); });
這樣就能實現(xiàn)手動上傳文件了。
3.遇到的坑
第一次選擇完文件,點擊上傳。第二次在打開Model發(fā)現(xiàn)上回的文件列表還在,我在網(wǎng)上找的方法是給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視頻教程》