如何验证多个文件的最大文件大小为每个文件 2 MB? (验证)

How can I validate the maximum file size is 2 mb per file for multiple files? (vuetify)

我正在尝试在 Vuetify 的 v-file-input 上设置验证规则以将文件大小限制为 2MB,但是当我 select 文件小于 2MB 时验证错误地失败(并出现输入错误) .

我的摘录 Codepen

<v-file-input
  multiple
  :rules="rules"
  accept="image/jpg, image/jpeg, application/pdf"
  placeholder="Pick an avatar"
  prepend-icon="mdi-camera"
  label="Avatar"
></v-file-input>

<script>
  //...
  data: () => ({
    rules: [
      value => !value || value.size < 2000000 || 'Avatar size should be less than 2 MB!',
    ],
  }),
  //...
</script>

我该如何解决这个问题?

好吧,我还没有测试过,但像这样的东西应该有用。在您的上传方法中,遍历输入文件并检查它们是否都小于 2mb:

const input = event.target
let files = input.files
//loop through this to check all the file sizes.
const isLt2M = files[0].size / 1024 / 1024 < 2;

问题是您的 v-file-input 接受多个文件,因此验证规则的参数实际上是 File 个对象的数组(即使只选择了一个文件)。规则函数应与此类似:

files => !files || !files.some(file => file.size > 2e6) || 'Avatar size should be less than 2 MB!'

规则使用 Array.prototype.some on the files array to determine if any of the file sizes are over 2 * 10^6. However, since file sizes are in terms of bytes, I recommend comparing to 2MiB 代替(即 2 * 1024 * 1024 = 2_097_152)。

演示:

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: () => ({
    rules: [
      files => !files || !files.some(file => file.size > 2_097_152) || 'Avatar size should be less than 2 MB!'
    ],
  }),
})
<script src="https://unpkg.com/vue@2.6.11/dist/vue.min.js"></script>
<script src="https://unpkg.com/vuetify@2.2.11/dist/vuetify.js"></script>
<link rel="stylesheet" href="https://unpkg.com/vuetify@2.2.11/dist/vuetify.min.css">
<link rel="stylesheet" href="https://unpkg.com/@mdi/font@4.9.95/css/materialdesignicons.min.css">

<div id="app">
  <v-app id="inspire">
    <v-file-input
      multiple
      :rules="rules"
      accept="image/jpg, image/jpeg, application/pdf"
      placeholder="Pick an avatar"
      prepend-icon="mdi-camera"
      label="Avatar"
    ></v-file-input>
  </v-app>
</div>