reactjs 如何在Ant Design中手动显示带有上传的base64图像?

hjzp0vay  于 2022-11-04  发布在  React
关注(0)|答案(1)|浏览(360)

我在Ant Design中使用Upload Manually上传文件,但它无法将预览图像显示为base64。当我从浏览器中选择图像时,我想将预览图像base64显示为图片卡。我如何修复它?
我的代码上传:

const FormPost = () => {
    const [fileList, setFileList] = useState([]);
    const [uploading, setUploading] = useState(false);

    const onFinish = (values) => {
        console.log('Success:', values);
    };
    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };

    const normFile = (e) => {
        console.log('Upload event:', e);
        if (Array.isArray(e)) {
            return e;
        }
        return e?.fileList;
    };

    const uploadProps = {
        onRemove: (file) => {
            const index = fileList.indexOf(file);
            const newFileList = fileList.slice();
            newFileList.splice(index, 1);
            setFileList(newFileList);
        },
        beforeUpload: (file) => {
            setFileList([...fileList, file]);
            return false;
        },
        listType: 'picture-card',
        fileList,
    };

    return (
        <Form layout="vertical" name="new-post" onFinish={onFinish} onFinishFailed={onFinishFailed} autoComplete="off">

            <Form.Item label="Upload" valuePropName="fileList" getValueFromEvent={normFile}>
                <Upload {...uploadProps}>
                    <div>New photo</div>
                </Upload>
            </Form.Item>

        </Form>
    );
};
gz5pxeao

gz5pxeao1#

前几天我也在想这个问题,关键是要用用户选择的文件的["thumbUrl"]属性,我是这样解决的:
如果是Upload组件的定义方式:

<Upload                               
      action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
      listType="picture-card"
      fileList={params.fileList}
      onChange={params.onChange}
      onPreview={params.onPreview}
      >
             {params.fileList.length === 0 && '+ Upload'}
</Upload>

它应该是您尝试向用户显示的Image组件:

<Image
     width={'80%'}
     height={'60%'}
     src={params.fileList[0]["thumbUrl"]}
/>

相关问题