简体   繁体   English

VueJS - 验证表单文件上传中的文件大小要求

[英]VueJS - Validate file size requirement in form file upload

I am using a Bootstrap Vue form to make a simple form where user can upload a file.我正在使用 Bootstrap Vue 表单制作一个简单的表单,用户可以在其中上传文件。 Is there a way to validate the size of files selected using Vue form ?有没有办法验证使用 Vue 表单选择的文件的大小?

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我更喜欢没有的解决方案

Here's a generic Vue example of how to validate the file's size before the form is submitted.这是一个通用的 Vue 示例,说明如何在提交表单之前验证文件的大小。

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;关键是从输入本身的files属性获取文件对象,并通过size属性检查文件的大小; 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM