I am using template (https://primevue.org/fileupload/#template), and would like to access maxFileSize error from a method in order to show it in a toast component. Is it possible?
If you use the maxFileSize
property of the FileUpload
component, its internal error handler will automatically be triggered. Unfortunately, there is no hook provided for this. The built-in max-file-size validation triggers an error for the file selection even before the select event
is called.
You can bypass this by leaving the maxFileSize
value at its default null
and writing your own maximum file size checker in the file select event
, where you can define custom actions. Remember, in this case, it will be your responsibility to remove the file from the input field (with remove()
API function) if it exceeds the allowed size.
const { createApp, ref } = Vue;
const app = createApp({
setup() {
const fileUploader = ref(null);
const MY_CUSTOM_MAX_FILE_SIZE = 1 * 1024 * 1024; // 1 MB
const onSelect = (event) => {
// Check if the error is due to maxFileSize
if (MY_CUSTOM_MAX_FILE_SIZE !== null) {
const { files } = event
files.forEach((file) => {
if (file.size > MY_CUSTOM_MAX_FILE_SIZE) {
// Custom error handling
const maxSizeMB = (MY_CUSTOM_MAX_FILE_SIZE / 1024 / 1024).toFixed(2);
const receivedSizeMB = (file.size / 1024 / 1024).toFixed(2);
console.error(`Error: File size exceeds the allowed limit. Max size: ${maxSizeMB} MB, Received size: ${receivedSizeMB} MB`);
// Manually remove from files
fileUploader.value.remove(file);
}
});
}
}
return {
fileUploader,
onSelect,
};
},
});
app.use(PrimeVue.Config, {
theme: {
preset: PrimeVue.Themes.Aura,
},
});
app.component('p-fileupload', PrimeVue.FileUpload);
app.mount('#app');
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script src="https://unpkg.com/primevue/umd/primevue.min.js"></script>
<script src="https://unpkg.com/@primevue/themes/umd/aura.min.js"></script>
<div id="app">
<p-fileupload
ref="fileUploader"
url="/nonexistent-url-error-simulation"
@select="onSelect"
:auto="true"
/>
</div>
remove
API function - PrimeVue Docs