英文:
File type validation in strapi v4
问题
我正在使用Strapi作为我的后端。我在集合中有一些字段,其中一些应该只接受zip文件,而另一些应该只接受图像等。
尽管我没有选择图像作为数据类型,但当我在Postman中传递一个图像到字段时,它仍然接受图像,我认为这是显而易见的行为,因为图像也是一种文件类型。
我的问题是,是否可以进行任何验证,以便这些字段只允许上传zip文件或我想要上传的任何文件类型?
英文:
I am using strapi as my backend. I have some fields in collection from which some should accept only zip file while some should accept only images etc.
I selected file type from datatypes available in strapi.
Though I have not selected images as data type but when I hit the endpoint with postman passing an image in the field then it accepts the image which I believe that obvious behavior as image is also one type of file.
My question is that is there any validation I can put such that these fields should allow only zip or whatever type of file I want to upload?
答案1
得分: 1
没有已知的内置解决方案来验证字段,但在实体创建过程开始之前有一些执行选项:
- 模型生命周期,
beforeCreate
事件 - 策略
- 中间件
所以 Google 建议,如果抛出错误,beforeCreate
应该阻止实体创建:
首先,让我们创建一个包含 media
字段并接受 single
媒体文件的内容类型。
让我们为此内容类型创建生命周期文件:
src/api/contentType/content-types/contentType/lifecycles.js
const { ForbiddenError } = require("@strapi/utils").errors;
module.exports = {
beforeCreate(event) {
const { data, where, select, populate } = event.params;
// 请注意,如果您通过管理界面创建,该行可能会有所不同
const media = await strapi.db
.query("plugin::upload.file")
.findOne({ where: { id: data.media } });
if (media.mime !== "application/x-zip-compressed")
throw new ForbiddenError("文件不是 ZIP 格式");
}
}
备注:如果您通过 rest api
创建,与 media
相关的部分可能会不同。
英文:
there is no known build in solution for validating fields, however there is few options that executing before entity creation process started:
- model lifecycle,
beforeCreate
event - policy
- middleware
So google suggests beforeCreate
should prevent entity creation if you throw an error:
First, let's create an content-type that has media
field that accepts single
media file.
let's create lifecycles file for this content type:
src/api/contentType/content-types/contentType/lifecycles.js
const { ForbiddenError } = require("@strapi/utils").errors;
module.exports = {
beforeCreate(event) {
const { data, where, select, populate } = event.params;
// PLS NOTE THAT LINE MAYBE DIFFERENT IF YOU CREATE FROM ADMIN VS REST
const media = await strapi.db
.query("plugin::upload.file")
.findOne({ where: { id: data.media } });
if (media.mime !== "application/x-zip-compressed")
throw new ForbiddenError("File is not ZIP");
}
P.S. Tested with create
from admin ui
if you create via rest api
the part with media
maybe different
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论