关于文件上传(antd upload)

2,921 阅读1分钟
  1. upload的使用
const pdfprops = {
            name: 'file',
            headers: {
                authorization: 'authorization-text',
            },
            beforeUpload: file => {
                console.log('yes')
    -------------------------return false:不上传 只展示------------------
                return false;
            },
            onChange: info => {
    -------------------------上传后的文件存在info中------------------------
                let file = info.file
    -------------------------判断上传的文件类型是否为所需------------------
                const ispdf = file.type === 'application/pdf';
                if (!ispdf) {
                    message.error('请上传pdf文件!');
                } else {
                    console.log('info',info)
                    
                    let fileList = [...info.fileList];
    ------------------fileList.slice:控制上传的文件个数--------------------
                    fileList = fileList.slice(-1);
                    fileList = fileList.map(file => {
                        if (file.response) {
                            file.url = file.response.url;
                        }
                        return file;
                    });
    ------------------将上传的文件存在state中设好的空数组里------------------
                    this.setState({ pdffileList:fileList });
                }
                return false
            },
        };
        
        
    -------------{...pdfprops}:实现设置的pdfprops内的功能-------------   
    -------------fileList:已经上传的文件列表,有改变时调用onchange---------
    <Upload {...pdfprops} fileList={this.state.pdffileList}>
        {pdfUrl ? <img src={pdfUrl} style={{ width: '100%' }} alt="avatar" /> : <>
            {oldpdfurl ? <img src={urlHOST + oldpdfurl} style={{ width: '100%' }} alt="avatar" /> :
                <Button>
                    <UploadOutlined /> 选择文件
                </Button>
            }
        </>}
    </Upload>
  1. 将文件传给后端
onCreate = async () => {
        const { pdffileList,imagefileList,oldimageurl,oldpdfurl } = this.state;
        if (imagefileList.length == 0&&oldimageurl=='') {
            message.error('未选择图片')
            return
        } 
        if (pdffileList.length == 0&&oldpdfurl=='') {
            message.error('未上传项目报告书PDF格式文档')
            return
        }
        try {
            const value = await this.addformRef.current.validateFields();
            const { wordfileList,pdffileList,jpgfileList,imagefileList } = this.state;
            const formData = new FormData();
            if (imagefileList.length > 0) {
                console.log("照片",imagefileList)
    --------------imagefileList为数组,文件存在了其下的originFileObj中-------
                imagefileList.forEach(file => {
                    console.log("照片文件",file.originFileObj)
                    formData.append('pictures[]', file.originFileObj);
                });
            } else {
    ------------------编辑情况下 未修改img传原url-------------------------
                formData.append('picture_urls', oldimageurl)
            }
            if (pdffileList.length > 0) {
                pdffileList.forEach(file => {
                    formData.append('project_report_pdf', file.originFileObj);
                });
            } else {
    ---------------------编辑情况下 未修改pdf传原url-----------------------
                formData.append('project_report_url', oldpdfurl)
            }
    ---------------------form表单中的其他非文件数据-------------------
            formData.append('case_name', value.casename)
            formData.append('category', this.state.category*1)
            let config = {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            }
    ----------------------------当id存在时即为修改------------------------
            if (this.state.id) {
                let id = this.props.match.params.id * 1
                formData.append('news_id', id)
                post('/player/upload', formData, config).then(res => {
                    message.success('修改成功')
                }).catch(res => {

                })
            } else {
    ----------------------------当id不存在时即为添加------------------------
                post('/player/upload', formData, config).then(res => {
                    message.success('添加成功')
                    console.log(res)
                }).catch(res => {

                })
            }
        }catch (errorInfo) {
            console.log('Failed:', errorInfo);
        }
    }
  1. addformRef
addformRef = React.createRef();
----------------------------------设置初值------------------------------------
 this.addformRef.current.setFieldsValue({
    case_name: res.case_name,
    class: res.category * 1
});
----------------------------------获取value值------------------------------------
const value = await this.addformRef.current.validateFields();

<Form ref={this.addformRef}>
</Form>


  1. FormData
const formData = new FormData();

formData.append('picture_urls', file.suburl)