reactjs - 使用 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>
我需要在不同的情况下对图像、音频文件和视频文件执行此操作,但我不知道如何解析特定的文件类型。
解决方案
我没有尝试使用文件类型验证插件,但我知道如果您在 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
希望有帮助!
推荐阅读
- python-3.x - 在 Ubuntu 18.04 上,包“python3-apt”处于不连贯状态
- python-3.x - 基于终端的高度,如何使用Python确定一次可以在其中显示的行数?
- bash - RabbitMQ Docker Bash 脚本问题 - .sh 未找到
- pandas - 如何在 matplotlib 的 mpl_connect 中使用悬停事件
- python - 在云中部署 Python 自动化脚本
- npm - Azure DevOps 管道 - 尝试连接到私有 npm 注册表时身份验证失败
- c++ - C ++旋转由9个字符数组组成的3x3网格?
- matlab - 与 Matlab 中的 NumericRuler 属性一致
- python - 为什么我在 GCP 中部署的 XGBoost 模型返回空预测?
- javascript - TripleDES 加密在 C# 和 JavaScript (CryptoJS) 中有不同的结果