ant-design中的upload实现文件与表单一起上传

关键点:

  1. 在上传前将文件信息保存
  2. 将文件传给后台
    由于我们使用的是ant-design中的upload组件,翻看官方文档可以看到beforeUpload是上传文件之前的钩子,它的参数为上传文件,并且如果它返回false,就会停止上传


    image.png

所以我们只要在beforUpload函数中设置保存文件信息,并且返回false,就可以实现第一步——在上传前将文件信息保存。具体代码如下:


<Upload
        name="file"
            
        maxCount={1}
        // fileList
        beforeUpload={file => {
                                        
            this.setState(state => ({
                            fileList: [...state.fileList, file],
                            }))
                            return false;
                    }}
            onRemove={fileList=>{
                                            
                    this.setState(state=>{
                    const index=state.fileList.indexOf(file);
                    const newFileList=state.fileList.slice();
                    newFileList.splice(index,1);
                    return {
                            fileList:newFileList
                            }
                            })
                            }}
                >
                    <p className="ant-upload-drag-icon">
                        <InboxOutlined />
                    </p>
                <p className="ant-upload-text">点击上传文件</p>
    </Upload>

接下来就是将文件传给后台的问题,我们可以通过将文件信息传入FormData实现:

<Button onClick={() => {
                        const {fileList}=this.state;
                        let formData=new FormData();
                        // fileList.forEach(file=>{
                        //  formData.append('file',file)
                        // });
                        formData.append('file',fileList[0])//只取第一个
                        this.props.dispatch({
                            type:'record/entryInfo',
                            payload:formData
                            }).then((res)=>{
                            this.setState({errorList:res});
                            })
                                        
                    }} 
        size="large" 
        type="primary"
       loading={loading}>
        导入
    </Button>

注意将文件传给后台时,若后台接收的content-type类型为mutipart/form-data,那我们在前端时不要设置content-type,否则会报错

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容