目录
  • antd upload上传组件获取服务端返回数据
    • 我是这样解决的
  • antd的upload上传组件uploading状态踩坑记
    • 说明
  • 总结

    antd upload上传组件获取服务端返回数据

    项目中使用到antd upload组件上传的问题,按照官网示例,获取不到返回的值,后面上去GitHub找了找解决办法,

    在upload返回值中,文件会有一个状态:status为done或者error的时候会返回一个response字段,这个字段里面会包含接口返回的数据,因此只需要坐下过滤就可以拿到值了

    我是这样解决的

    antd upload上传组件如何获取服务端返回数据

    上面的判断可以过滤掉,哪个是判断多张上传出错的时候  给一个提示,因为antd upload组件多张上传 会走多次beforeupload方法,会提示多次。

    回归正题,这样判断之后就可以拿到对应的数据,数据的处理就看自己的了,但是需要注意的就是如果是自己自定义的数据,数据中必须要有uid字段,不然会报错。

    还有就是上传的时候会多次走upload方法,每一次都需要给你的filelist赋值,不然后续的upload方法就不会走,也就不会调取接口了.

    antd的upload上传组件uploading状态踩坑记

    说明

    在使用Antd 的 Upload 组件 的onChange()方法中,打印fileList 中的文件状态status 一直是 uploading,无法拿到上传文件后服务端响应的内容,且组件下方不显示文件列表问题

    以下是解决方法:

    const Dragger = Upload.Dragger;
    constructor(props) {
            super(props);
            this.state = {
                fileList: [],
            };
        }
    <Dragger
                            listType={"picture"}
                            action={uploadUrl}
                            accept={acceptPictype}
                            disabled={upLoadDisabled}
                            beforeUpload={() => {
                            }}
                            fileList={isScanSuccess?[]:this.state.fileList}
                            onChange={
                                (data) => {
                                    console.log(data)
                                    const { fileList, file } = data;
                                 		//自己的逻辑
                                        this.setState({ fileList: [...fileList] });//这段代码放在处理逻辑的最后面  
                                    }                           
                                }
                            }
                        >
    在github[解答](https://github.com/ant-design/ant-design/issues/2423)上此问题解答:
    
    对于受控模式,你应该在 onChange 中始终 setState fileList,保证所有状态同步到 Upload 内。类似这里的写法:http://ant.design/components/upload/#components-upload-demo-fileList
    
    // good  正确写法
    
    onFileChange(fileList) {
      if ( ... ) {
        ...
      } else {
        ...
      }
      // always setState
      this.setState({ fileList: [...fileList] });
    }
    <Upload fileList={this.state.fileList} onChange={this.onFileChange} />
    // bad 写法
    onFileChange(fileList) {
      if ( ... ) {
        this.setState({ fileList: [...fileList] });
      } else {
        ...
      }
    }
    <Upload fileList={this.state.fileList} onChange={this.onFileChange} />
    建议研习受控组件概念:https://facebook.github.io/react/docs/forms.html#controlled-components
    注意需要克隆 fileList 以保障 Upload 能感知数组变化。
    - this.setState({ fileList });
    + this.setState({ fileList: [...fileList] });
    
    

    总结

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

    声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。