简体   繁体   English

如何删除文件上传中的错误消息?

[英]How to remove error message in file upload?

I am making a file upload using antd design and here we are allowing the user to upload only JPEG images.我正在使用antd design上传文件,这里我们只允许用户上传JPEG图片。

Here we have set the rules to upload only maximum of 3 JPEG images.在这里,我们设置了最多只能上传3JPEG图片的规则。

rules={[
          { required: true },
          { max: 3, message: "Only 3 attachments are allowed", type: "array" }
        ]}

Issue:问题:

Here when we upload 3 JPEG files, it is fine.这里当我们上传 3 个JPEG文件时,就可以了。

If we upload 4th file as JPEG , the error is showing which is also fine.如果我们将第 4 个文件上传为JPEG ,则显示错误也没有问题。

But when we upload 4th file as invalid file, the error still shows which is incorrect.但是当我们上传第 4 个文件作为无效文件时,错误仍然显示哪个不正确。

Steps to Reproduce:重现步骤:

-> Upload 3 JPEG files, -> 上传 3 个JPEG文件,

-> Upload 4th file which is in another format not JPEG . -> 上传不是 JPEG的另一种格式的第 4 个文件。

If you observe the results, the uploaded file will be ignored in UI but we still see the error message as Only 3 attachments are allowed .如果您观察结果,上传的文件将在 UI 中被忽略,但我们仍然会看到错误消息Only 3 attachments are allowed

在此处输入图像描述

See the above image for better representation.请参阅上图以获得更好的表示。 Uploading 4th file as .html format and hence getting error in the modal popup which is correct but the rules error message (in text after last file) still displays even though there are only 3 files in the UI.将第 4 个文件上传为.html格式,因此在模式弹出窗口中出现错误,这是正确的,但规则错误消息(在最后一个文件后的文本中)仍然显示,即使 UI 中只有 3 个文件。

Working Sandbox:工作沙箱:

编辑 antd-file-upload-validation-in-reactjs (forked)

I see the issue might be from the line 46 - 51 which has,我看到问题可能来自第46 - 51行,其中有,

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

The above line returns the uploaded files hidden even though it exceeds the limit.上面的行返回隐藏的上传文件,即使它超过了限制。

Kindly please help me to resolve the above issue as I am stuck for long time and big thanks in advance.请帮助我解决上述问题,因为我被困了很长时间,非常感谢。

The problem is that even you see three files in UI but the error that appears below the files because you are using antd form and anything that wrapped with <Form.Item> and having a name attribute, it is controlled by antd form.问题是,即使您在 UI 中看到三个文件,但错误出现在文件下方,因为您使用的是 antd 表单和任何用 <Form.Item> 包装并具有name属性的东西,它由 antd 表单控制。 By passing fileList state to Upload component, this does not mean that you are controlling the fileList and you have exactly 3 files.通过将fileList state 传递给上传组件,这并不意味着您正在控制 fileList 并且您正好有 3 个文件。 To prove this, let me you give an example:为了证明这一点,让我举个例子:

1. Upload 3 jpeg files and get the values of attachment using form.getFieldValue('attachment') . 1.上传 3 个 jpeg 文件并使用form.getFieldValue('attachment')获取附件的值。 Expected Result: An array with 3 files, No Error Below the files预期结果:包含 3 个文件的数组,文件下方无错误

2. Upload one more jpeg or any file & check the attachment value with form.getFieldValue('attachment') Expected Result: An array of files with length 4 & it should be 3 files in the array according to you. 2.再上传一个 jpeg 或任何文件,并使用form.getFieldValue('attachment')检查附件值预期结果:一个长度为 4 的文件数组,根据您的说法,它应该是数组中的3 files Also an error that doesn't disappear.也是一个不会消失的错误。

There are two problems in your code.您的代码中有两个问题。
Problem 1: As you said if you upload 4 file that is jpeg after uploading 3 jpeg files, i still see 4 files in UI.问题 1:如您所说,如果您在上传 3 个 jpeg 文件后上传 4 个 jpeg 文件,我仍然会在 UI 中看到 4 个文件。
Solution: Don't add more files in fileList if its already have 3 files.解决方案:如果 fileList 已经有 3 个文件,则不要在 fileList 中添加更多文件。 In beforeUpload, replace setFileList((prev) => [...prev, file]);在 beforeUpload 中,替换setFileList((prev) => [...prev, file]); with the following code:使用以下代码:

setFileList((prev) => {
    if (prev.length < 3) {
        return [...prev, file];
    }
    return prev;
});

Second Problem: Error doesn't disappears even you have 3 files in UI.第二个问题:即使您在 UI 中有 3 个文件,错误也不会消失。
Solution: You can use onChange Function. You can check if info.fileList have length greater than 3, then just replace the form attachment value with the original fileList.解决方案:可以使用onChange Function。可以检查info.fileList的长度是否大于3,然后将表单附件值替换为原始fileList即可。 I set a timeout to show the error that you can upload 3 attachments and remove the error message after 2 second.我设置了一个超时来显示你可以上传 3 个附件的错误,并在 2 秒后删除错误消息。

onChange: (info) => {
    if (info.fileList.length > 3) {
        setTimeout(() => form.setFieldsValue({ attachment: fileList as any }), 2000);
    }
}

Hope this solve your issue.希望这能解决您的问题。

Complete Code完整代码

import { useState, useMemo } from 'react';
import { Upload, Button, message, Form } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { UploadFile, UploadProps } from 'antd/lib/upload/interface';
import { RcFile } from 'rc-upload/lib/interface';

interface FormRule {
    title: string;
    attachment?: { file: RcFile; fileList: RcFile[] };
}

const Uploader = () => {
    const [fileList, setFileList] = useState<UploadFile<any>[]>([]);
    const [form] = Form.useForm<FormRule>();

    const validateFileType = ({ type, name }: UploadFile, allowedTypes: string[] = ['image/jpeg']) => {
        return allowedTypes.includes(type!);
    };

    const uploadProps = useMemo(
        () =>
            ({
                multiple: true,
                beforeUpload: (file: UploadFile) => {
                    const isAllowedType = validateFileType(file);
                    if (!isAllowedType) {
                        message.error(`${file.name} is not JPEG file`);
                        return false;
                    }
                    setFileList((prev) => {
                        if (prev.length < 3) {
                            return [...prev, file];
                        }
                        return prev;
                    });
                    return false;
                },
                onRemove: (file: UploadFile) => {
                    setFileList((prev) => prev.filter((item) => item.uid !== file.uid));
                },
                onChange: (info) => {
                    if (info.fileList.length > 3) {
                        setTimeout(() => form.setFieldsValue({ attachment: fileList as any }), 2000);
                    }
                }
            } as UploadProps),
        [fileList]
    );

    const onSubmit = async (data: FormRule) => {
        console.log('data');
    };

    const normFile = (e: any) => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    };

    return (
        <Form form={form} onFinish={onSubmit} layout='vertical'>
            <Form.Item
                name='attachment'
                valuePropName='attachment'
                getValueFromEvent={normFile}
                rules={[{ required: true }, { max: 3, message: 'Only 3 attachments are allowed', type: 'array' }]}
            >
                <Upload {...uploadProps} fileList={fileList}>
                    <Button icon={<UploadOutlined />}>Upload JPEG only</Button>
                </Upload>
            </Form.Item>

            <Button type='primary' htmlType='submit'>
                Submit
            </Button>
        </Form>
    );
};

export default Uploader;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM