How to disable the default behavior of Ant-Design Vue Upload Component.

Guide to limit the file list to one file, persist it in your data model and validate the file size with Ant FormModel.

Fabian Skarmeta
devsChile
3 min readJul 24, 2021

--

If you just want to persist an upload file and add it to your model for some further action, like a post or put request, the default Upload Component doesn’t behave intuitively for that. It’s more likely build to directly handle uploads once the user has selected many files.

In this guide we will:
1) Limit the Upload Component list to just one file.
2) Limit the maximum size of the file.
3) Combine this last step with a custom validation integrated to the Ant FormModel.
4) Save the file in our form model.

We will assume you know how the Ant-Design Vue FormModel behaves, if not, you can take a look at the documentation here https://antdv.com/components/form-model/

So, in short, let’s say we have this Ant Upload set up in our template.

Custom Ant Design Vue Upload Component

Let’s also say that we will handle multiple uploads, so just to save some lines, we will define a validation message between our imports and the script tag.

Just bear with me for one moment, but our final data() section will include this.

As you see, we will have these two functions in our methods section to validate the file size. In this example, to 5 MB maximum.

maxFileSize(size) {
 return size < 400000
 },
 async handleExceedSize(rule, value, cb) {
 const file = await value
 if (file) {
 if (!this.maxFileSize(file.size)) {
 return cb(‘The file exceeds the maximum size’)
 }
 cb()
 }
 },

Lastly, we also handle our upload events in our methods section.
Within the beforeUplad method, we assign the file to our model and update the file list so it’s always limited to one file. Here, the “return false” statement is indeed the key to deactivate the default behavior of the Upload Component.

Finally, when a file is removed by the user from the list, we update the form model and the file list.

That would be all friends, I hope you found this information useful.
You can always reach me out on Twitter.
https://twitter.com/fskarmeta
Happy coding!

--

--

Fabian Skarmeta
devsChile

German an chilean producer, jazzist, writer, developer and gamer. Into global politics, news and crypto markets.