For the most part with file uploads we want to accomplish two main tasks.
The guide covers setting up the most common file upload usage for profile avatars.
It's best to take a look at the demo code available on GitHub and try it out for yourself.
At a minimum the url
option must be set when creating a new $upload
instance.
this.$upload
.on('avatar', {
url: 'users/1/avatar'
});
The avatar
is a name for the instance that is also required. This allows us to create multiple upload instances.
It's important to note that we can also destroy an instance. This is a good practice if we no longer need the instance as in the case of a user account profile page.
this.$upload
.off('avatar');
It's likely the url endpoint for the upload will be dynamic.
For instance the user id
would not be static, so we can use the option()
method to change it on the fly.
created() {
this.$upload
.on('avatar', {
onSuccess(res) {
// Update user avatar
}
});
},
methods: {
click(user) {
this.$upload
.option(
'avatar',
'url', 'users/' + user.id + '/avatar'
);
this.$upload
.select('avatar');
}
},
The upload instance will maintain an array of all files in the upload regardless of it being single or multiple file upload.
There are two methods for this named files()
and file()
with the latter being a shortcut reference to the files().all[0]
queue file object.
The object exposes a lot of useful properties to show the state of the current upload.
<template>
<div>
{{ file.name }}
{{ file.size }}
{{ file.type }}
{{ file.state }}
{{ file.percentComplete }}
{{ file.errors | json }}
</div>
</template>
<script>
export default {
computed: {
file() {
return this.$upload.file('avatar');
}
}
}
</script>
There is more detailed information on the File Queues Guide which covers more advanced usage.
The plugin also includes an errors()
method that includes a global stack of local and API file errors.
For instance checking valid extensions or size is done locally in the browser and will add an internal error.
Some cases like total files selected exceeding the max files count can also throw an error without a file being added to the queue. In this the $file
object in the error will be null
since it serves as a general error.