VueJS-验证表单文件上传中的文件大小要求 [英] VueJS - Validate file size requirement in form file upload

查看:518
本文介绍了VueJS-验证表单文件上传中的文件大小要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Bootstrap Vue表单制作一个简单的表单,用户可以在其中上传文件.有没有一种方法可以验证使用Vue表单选择的文件的大小?

I am using a Bootstrap Vue form to make a simple form where user can upload a file. Is there a way to validate the size of files selected using Vue form ?

我要阻止用户上传此类文件.

I want to prevent user from uploading such files.

我见过解决方案,但看起来像包括一些第三方插件.我更喜欢一个不会​​的解决方案

I have seen this solution but looks like it includes some third party plugin. I prefer a solution which doesn't

推荐答案

下面是一个通用的Vue示例,说明如何在提交表单之前验证文件的大小.

Here's a generic Vue example of how to validate the file's size before the form is submitted.

问题的关键在于从输入本身的files属性获取文件对象,并通过size属性检查文件的大小;其余只是与验证失败时阻止提交表单有关的内容.

The crux is obtaining the file object from the files property on the input itself, and checking the file's size via the size property; the rest is just stuff related to preventing the form from being submitted if the validation fails.

不用说,但是重要的是诸如此类的任何输入验证都应该首先在服务器上进行;客户端验证可增强用户体验,但不提供安全性.

It goes without saying, but it is important that any kind of input validation such as this should be done on the server first and foremost; client-side validation enhances the user experience but provides no security.

new Vue({
  el: '#app',
  methods: {
    onSubmit(e) {
      const file = this.$refs.file.files[0];
      
      if (!file) {
        e.preventDefault();
        alert('No file chosen');
        return;
      }
      
      if (file.size > 1024 * 1024) {
        e.preventDefault();
        alert('File too big (> 1MB)');
        return;
      }
      
      alert('File OK');
    },
  },
});

<script src="https://rawgit.com/vuejs/vue/dev/dist/vue.js"></script>

<div id="app">
  <form @submit="onSubmit">
    <input type="file" ref="file">
    <button type="submit">Submit</button>
  </form>
</div>

这篇关于VueJS-验证表单文件上传中的文件大小要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆