首页 > 解决方案 > 使用 Filepond 在 ReactJS 中验证文件类型

问题描述

我已经使用 Yii2 框架和 ReactJS 在 ReactJS 中成功实现了文件上传。但我很乐意在上传之前验证文件的文件类型。我遇到过这个问题,我尝试将其实现为:

<FilePond
    ref={ref => this.pond = ref}
    files={this.state.coverfiles}
    acceptedFileTypes={['images/*']}
    fileValidateTypeDetectType={(source, type) => new Promise((resolve, reject) => {
        
        resolve(type);
     })
    }
    onupdatefiles={(fileItems) => {
          // Set current file objects to this.state
          this.setState({
              coverfiles: fileItems.map(fileItem => fileItem.file)
          });
      }}
    required={true} 
    name={'coverfiles'} 
    //instantUpload={this.state.sumitted}
    allowImageCrop={true}
    allowMultiple={false} 
    processFile={false}
    
    labelIdle={'Drag and Drop your Cover Add Picture or <span class="filepond--label-action"> Browse </span>'}
    
    >
</FilePond>

我需要在不同的情况下对图像、音频文件和视频文件执行此操作,但我不知道如何解析特定的文件类型。

标签: reactjsvalidationfile-uploadfile-typefilepond

解决方案


我没有尝试使用文件类型验证插件,但我知道如果您在 FilePond 上设置服务器属性并覆盖处理功能,则可以进行一般的预上传验证。由于 File 对象作为参数公开给该函数,因此您可以查询 file.type 以获取 MIME 类型作为字符串并拒绝。

为了符合我的 API,我需要重写它以进行我需要的其他一些清理,因此这只是我所有预上传验证(文件大小、名称重复等)的自然点。

在实践中大致看起来是:

<FilePond
    allowMultiple
    server={
             {  process: (fieldName, file, metadata, load, error, progress, abort) => {
                    if (file.type.includes('image')) {
                        error(new Error('Invalid file type'));
                    } else {
                        load(file.name);
                    }
                }
             }
           }
/>

相关文档在这里:https ://pqina.nl/filepond/docs/patterns/api/server/#introduction

此外,file.type 验证不是确定文件类型的完美方法,因为它不读取字节流,只是根据扩展名进行解析。请参阅 MDN 上关于在此处使用 File.type 的建议:https ://developer.mozilla.org/en-US/docs/Web/API/File/type

希望有帮助!


推荐阅读