ANTD文件上传验证在ReactJ中

发布于 2025-01-21 06:22:57 字数 1740 浏览 0 评论 0 原文

我使用 antd design ,它使文件上传良好。

<Upload {...props}>
  <Button icon={<UploadOutlined />}>Upload png only</Button>
</Upload>

在这里,我有一个 toferplaod 函数,它的代码看起来

const beforeUpload = (file) => {
  const isPNG = file.type === "image/png";
  if (!isPNG) {
    message.error(`${file.name} is not a png file`);
  }
  // return Upload.LIST_IGNORE; (This will work in newer version but I am using older one which is 4.9.4.
}

像我在上述代码中提到的那样,如果上传的映像不是png,则它将从当前列表中删除一个上载,因为我们使用 upload.list_ignore ,但不幸的是,我正在版本4.9.4 中工作,并且没有任何这样的关键字可以从列表中删除无效的上传。

您能帮助我从版本4.9.4的列表中删除上传的无效项目吗?

工作示例:

“ a>

结果:

“在此处输入映像说明”

尝试过一些尝试后,我阻止了文件在列表中显示在列表中,如果该文件不有效,但不幸的是,上传文件的删除现在不起作用(之前正常工作当前的实现)。

I am having a file upload using Antd design and it makes the file upload fine.

<Upload {...props}>
  <Button icon={<UploadOutlined />}>Upload png only</Button>
</Upload>

Here I have a beforeUplaod function and its code looks like,

const beforeUpload = (file) => {
  const isPNG = file.type === "image/png";
  if (!isPNG) {
    message.error(`${file.name} is not a png file`);
  }
  // return Upload.LIST_IGNORE; (This will work in newer version but I am using older one which is 4.9.4.
}

As I have mentioned in the above code, if the uploaded image is not png then it will remove the uploaded one from current list as we use Upload.LIST_IGNORE but unfortunately I am working in a older version 4.9.4 and it doesn't have any such keyword to remove the inValid upload from the list.

Could you please kindly help me to remove the uploaded invalid item from the list for version 4.9.4?

Working example:

Edit antd upload component as file selector (forked)

Result:

enter image description here

After some try, I have prevented the file to display in the list if it is not valid but unfortunately the delete of the uploaded file doesn't work now (which was working fine before this current implementation).

Edit antd typescript (forked)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

花海 2025-01-28 06:22:57

我能够通过实现 onRemove 处理程序来删除选定/上传的文件。

示例:

const Uploader = () => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const validateFileType = (
    { type, name }: UploadFile,
    allowedTypes?: string
  ) => {
    if (!allowedTypes) {
      return true;
    }

    if (type) {
      return allowedTypes.includes(type);
    }
  };

  const uploadProps = useMemo(
    () => ({
      beforeUpload: (file: UploadFile) => {
        const isAllowedType = validateFileType(file, "image/png");
        if (!isAllowedType) {
          setFileList((state) => [...state]);
          message.error(`${file.name} is not PNG file`);
          return false;
        }
        setFileList((state) => [...state, file]);
        return false;
      },
      onRemove: (file: UploadFile) => {
        if (fileList.some((item) => item.uid === file.uid)) {
          setFileList((fileList) =>
            fileList.filter((item) => item.uid !== file.uid)
          );
          return true;
        }
        return false;
      }
    }),
    [fileList]
  );

  return (
    <Upload multiple {...uploadProps} fileList={fileList}>
      <Button icon={<UploadOutlined />}>Upload png only</Button>
    </Upload>
  );
};

” in-reaCtjs“>

I was able to get the removal of selected/uploaded files by implementing an onRemove handler.

Example:

const Uploader = () => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const validateFileType = (
    { type, name }: UploadFile,
    allowedTypes?: string
  ) => {
    if (!allowedTypes) {
      return true;
    }

    if (type) {
      return allowedTypes.includes(type);
    }
  };

  const uploadProps = useMemo(
    () => ({
      beforeUpload: (file: UploadFile) => {
        const isAllowedType = validateFileType(file, "image/png");
        if (!isAllowedType) {
          setFileList((state) => [...state]);
          message.error(`${file.name} is not PNG file`);
          return false;
        }
        setFileList((state) => [...state, file]);
        return false;
      },
      onRemove: (file: UploadFile) => {
        if (fileList.some((item) => item.uid === file.uid)) {
          setFileList((fileList) =>
            fileList.filter((item) => item.uid !== file.uid)
          );
          return true;
        }
        return false;
      }
    }),
    [fileList]
  );

  return (
    <Upload multiple {...uploadProps} fileList={fileList}>
      <Button icon={<UploadOutlined />}>Upload png only</Button>
    </Upload>
  );
};

Edit antd-file-upload-validation-in-reactjs

開玄 2025-01-28 06:22:57

您可以创建一个状态&amp;控制filelist。在新版本中,我们可以使用upload.list_ignore,但可以查看 api段。如果您不想上传文件,则可以简单地返回false或使用Promise,可以使用 recond(false)拒绝。

在上传组件的API部分中查看 the upload
https://ant.design/components/upload/upload/#api

import { useState } from 'react';
import { Upload, Button, message, UploadProps } from 'antd';
import { UploadOutlined } from '@ant-design/icons';

function App() {
    const [fileList, setFileList] = useState([]);
    const [mode, setMode] = useState(false);

    const uploadProps = {
        multiple: mode,
        fileList,
        beforeUpload: (file, filesArray) => {
            let count = 0;
            let files = filesArray.filter((file) => {
                const isPNG = file.type === 'image/png';
                !isPNG && count++;
                return isPNG;
            });

            if (count > 0) {
                setFileList([]);
                message.error(`${count} Files Not Uploaded. Please Upload PNG File/s`);
                return false;
            }

            // If Mode Is Multiple, Simply Store All Files
            if (mode) {
                setFileList(files);
            } else {
                setFileList((prev) => {
                    let newFiles = [...prev];
                    newFiles.push(file);
                    return newFiles;
                });
            }
            return true;

            // Using Promise
            // return new Promise((resolve, reject) => {
            //  // If Not PNG, Reject The Promise
            //  if (!isPNG) return reject(false);

            //  // Else Set The FileList & Send The File
            //  setFileList([file]);
            //  resolve(file);
            // });
        },
        onRemove: (file) => {
            setFileList((prev) => prev.filter((f) => f.uid !== file.uid));
        }
    };

    console.log(fileList);

    return (
        <div style={{ display: 'flex', flexDirection: 'column' }}>
            <div style={{ marginBottom: '10px' }}>
                <Button type='primary' onClick={() => setMode((prev) => !prev)}>
                    Toggle Mode
                </Button>
            </div>
            <Upload {...uploadProps}>
                <Button icon={<UploadOutlined />}>Upload png only</Button>
            </Upload>
        </div>
    );
}

export default App;

https://i.sstatic.net/lzgbm.png“ rel =“ nofollow noreferrer”>

希望这能解决您的问题

You can create a state & control the fileList. In new version, we can use Upload.LIST_IGNORE but have a look at the API Section. If you do not want to upload the file, you can simply return false or if you use promise, you can reject with reject(false).

Have a look at beforeUpload in API Section of Upload Component.
https://ant.design/components/upload/#API

import { useState } from 'react';
import { Upload, Button, message, UploadProps } from 'antd';
import { UploadOutlined } from '@ant-design/icons';

function App() {
    const [fileList, setFileList] = useState([]);
    const [mode, setMode] = useState(false);

    const uploadProps = {
        multiple: mode,
        fileList,
        beforeUpload: (file, filesArray) => {
            let count = 0;
            let files = filesArray.filter((file) => {
                const isPNG = file.type === 'image/png';
                !isPNG && count++;
                return isPNG;
            });

            if (count > 0) {
                setFileList([]);
                message.error(`${count} Files Not Uploaded. Please Upload PNG File/s`);
                return false;
            }

            // If Mode Is Multiple, Simply Store All Files
            if (mode) {
                setFileList(files);
            } else {
                setFileList((prev) => {
                    let newFiles = [...prev];
                    newFiles.push(file);
                    return newFiles;
                });
            }
            return true;

            // Using Promise
            // return new Promise((resolve, reject) => {
            //  // If Not PNG, Reject The Promise
            //  if (!isPNG) return reject(false);

            //  // Else Set The FileList & Send The File
            //  setFileList([file]);
            //  resolve(file);
            // });
        },
        onRemove: (file) => {
            setFileList((prev) => prev.filter((f) => f.uid !== file.uid));
        }
    };

    console.log(fileList);

    return (
        <div style={{ display: 'flex', flexDirection: 'column' }}>
            <div style={{ marginBottom: '10px' }}>
                <Button type='primary' onClick={() => setMode((prev) => !prev)}>
                    Toggle Mode
                </Button>
            </div>
            <Upload {...uploadProps}>
                <Button icon={<UploadOutlined />}>Upload png only</Button>
            </Upload>
        </div>
    );
}

export default App;

enter image description here

Hope this solve your problem

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文