{const { fileList } = this.state...}" Just submit the form and upload the file."/> {const { fileList } = this.state...}" Just submit the form and upload the file.">
Home > Article > Web Front-end > How to implement file upload in react
React method to implement file upload: 1. Introduce the required antd components through "import { Table, Button, Modal, Form, Input, Upload, Icon, notification } from 'antd';"; 2. Submit the form and upload the file through "handleOk = e => {const { fileList } = this.state...}".
The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.
How to upload files in react?
react uses antd to implement manual file upload (submit form)
Foreword: Recently I am working on a background management project that involves uploading files, using antd in Upload implements uploading files. Record the problems and pitfalls encountered.
1. The effect to be achieved
The effect I want to achieve is to click to upload the file, and click ok after selecting the file (that is, after submitting the form, Upload) is actually uploading files manually. Let me introduce my approach and some pitfalls I encountered.
2. Implementation steps
1.Introduce the required antd components
import { Table, Button, Modal, Form, Input, Upload, Icon, notification } from 'antd';
This is the form
<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>
The following code is the props of Upload
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, };
The following is the focus on submitting the form and uploading files
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 }); }) };
Note that I use axios, post must use formData.append ("Interface parameter name", "Value to be passed"); if you don't want to Using axios, you can also use other requests
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); });
so that you can upload files manually.
3. Pitfalls
After selecting the file for the first time, click Upload. When I opened the Model for the second time, I found that the file list from the last time was still there. The method I found online was to give upload and a key value, but the cache will disappear only after clicking ok and opening the Model for the second time, but it will still exist when I click canel.
<div key={Math.random()}> <Upload {...props}> <Button type="primary"> <Icon type="upload" />选择文件 </Button> </Upload> </div>
The best way is this.setState to empty the file list in the state
this.props.form.resetFields()//添加之前把input值清空 this.setState({ visible: true, fileList: [] //把文件列表清空 });
You can also add a destroyOnClose attribute to Modal to destroy the child elements in Modal when closing
Recommended learning: "react video tutorial"
The above is the detailed content of How to implement file upload in react. For more information, please follow other related articles on the PHP Chinese website!