VueJS - Validate file size requirement in form file upload

被刻印的时光 ゝ 提交于 2019-12-11 06:01:43

问题


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


回答1:


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

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>


来源:https://stackoverflow.com/questions/52142997/vuejs-validate-file-size-requirement-in-form-file-upload

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