How to validate multipart file on AdonisJS?

纵然是瞬间 提交于 2019-12-13 03:35:15

问题


I am using Adonis.js in the latest version but cannot validate... Already tried

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

Nothing works, the code lets you upload any type of file, like .pdf or .mp4

There's nothing in the Adonis.js documentation talking about it either.

Package version

Version 4.1 "@adonisjs/framework": "^5.0.9"

Node.js and npm version

NODE - v10.15.0 NPM - 6.10.1


回答1:


The validation rules do not work for the multipart file upload on adonis. You need to do manual validation. For example:

// 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)
})


来源:https://stackoverflow.com/questions/57193772/how-to-validate-multipart-file-on-adonisjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!