加入收藏 | 设为首页 | 会员中心 | 我要投稿 南京站长网 (https://www.025zz.com.cn/)- 自然语言处理、建站、经验、云计算、图像分析!
当前位置: 首页 > 教程 > 正文

react上如何实现文件上传

发布时间:2023-07-11 11:30:44 所属栏目:教程 来源:未知
导读:   本篇内容介绍了“react如何实现文件上传”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔
  本篇内容介绍了“react如何实现文件上传”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
 
  react实现文件上传的方法:1、通过“import { Table, Button, Modal, Form, Input, Upload, Icon, notification } from 'antd';”引入所需antd的部件;2、通过“handleOk = e => {const { fileList } = this.state...}”实现提交表单并上传文件即可。
 
  react使用antd实现手动上传文件(提交表单)
 
  1.要实现的效果
 
  react如何实现文件上传
 
  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 里的子元素。
 

(编辑:南京站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章