我正在使用最新版本的Adonis.js
,但是无法验证...
已经尝试
request.multipart.file('avatar', {
types: ['jpeg', 'jpg', 'png'], // I already tried -> type: ['image'] types: ['image'],
size: "4mb"
}, async file => {
await Drive.put(key, file.stream)
})
.../Validators/changeAvatar.js
'use strict'
class UserChangeAvatar {
get rules() {
return {
avatar: 'required|file|file_ext:png,jpg,jpeg,svg'
}
}
}
module.exports = UserChangeAvatar
无效,该代码使您可以上传任何类型的文件,例如.pdf
或.mp4
Adonis.js文档中也没有谈论它。
版本4.1
"@adonisjs/framework": "^5.0.9"
节点-v10.15.0 NPM-6.10.1
答案 0 :(得分:2)
验证规则不适用于在阿多尼斯上载的多部分文件。您需要进行手动验证。例如:
// Helper function
function fileStreamValidation(file, validationRules) {
const validationErrors = []
if (!RegExp(/^[0-9a-zA-Z_\-.]+$/).test(file._clientName)) {
validationErrors.push(
`${file._clientName}'s name should only contain alphanumeric, underscore, dot, hypen`
)
}
if (validationRules.extnames && validationRules.extnames.length) {
const [_, fileExtension] = file._clientName.split(/\.(?=[^.]+$)/)
if (!validationRules.extnames.includes(fileExtension)) {
validationErrors.push(`${file._clientName}'s extension is not acceptable`)
}
}
if (validationRules.maxFileSizeInMb) {
if (file.stream.byteCount > validationRules.maxFileSizeInMb * 1000000) {
validationErrors.push(`${file._clientName}'s size exceeded limit`)
}
}
return validationErrors
}
/* validation in controller */
const validationOptions = {
extnames: ['in', 'out'],
maxFileSizeInMb: parseInt(Env.get('MAX_FILE_SIZE_IN_MB'))
}
request.multipart.file('datasets[]', {}, async file => {
const errors = fileStreamValidation(file, validationOptions)
})