Search code examples
javascriptvue.jsprimevue

PrimeVue FileUpload - Handle server upload error


When uploading files, server might return an error. I can access the error through the event error:

@error="onUploadError"

However, I do not manage to manipulate the file list in order to remove them from preview. Is it a way to access the uploader-state?


Solution

  • You cannot directly modify the FileUpload component, but by defining it as a ref, you can clear it by calling an internal API function: clear().

    const { createApp, ref } = Vue;
    
    const app = createApp({
      setup() {
        const fileUploader = ref(null);
        
        const onUploadError = (event) => {
          console.error("Upload Error");
    
          // Access the FileUpload component via ref and clear the file list
          if (fileUploader.value) {
            fileUploader.value.clear();
          }
        }
    
        return {
          fileUploader,
          onUploadError,
        };
      },
    });
    
    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"
        @error="onUploadError"
        :auto="true"
      />
    </div>