[Vuejs]-How to reset an uploaded file once a button has been pressed

0👍

This feels like more of a <input type="file"> question than a VueJS one.

The file input provides javascript an API to read a file from the browser. The file input is not inherently aware of a) whether you’re uploading it or not or b) how to react once such a process has been completed.

As a consequence, what you’re missing is some code to clear out the file input once this process has been completed. In short, all you really need is something akin to fileInput.value = ''

Since this isn’t really a VueJS issue but more of a file input issue, here’s a minimal example of this without VueJS.

const upload = document.querySelector('#upload')
const btn = document.querySelector('#upload-btn')

// The 'input' event is fired when a file is selected
upload.addEventListener('input', (e) => {
  // In this example, we show the upload button only once a file is chosen
  if (e.target.value) {
    // A file was selected. So enable the upload button
    btn.removeAttribute('disabled')
  } else {
    // No file available. Disable the upload button
    btn.setAttribute('disabled', true)
  }
})

btn.addEventListener('click', async () => {
  // Do some async work here to pretend to be uploading
  btn.classList.add('is-loading')
  await new Promise(resolve => setTimeout(resolve, 1000)) // Simply sleeps for 1s
  btn.classList.remove('is-loading')
  upload.value = '' // Reset the file input
  
  // Dispatch the input event so that the other handler will 
  // run and disable the upload button
  const evt = new CustomEvent('input')
  upload.dispatchEvent(evt)
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.4/css/bulma.css" rel="stylesheet"/>
<p>
  This example shows how to clear a <code>file</code> input.<br>
  Click the 'Choose File' button to select any file. Once a file is selected, click the upload button.<br>
  <b>Note</b>: No real upload occurs. The button simply circles to <i>pretend</i> to upload and then resets the file input.
</p>
<div>
  <!-- Create a file input to work with -->
  <input id="upload" type="file">
</div>
<div>
  <!-- Create a button to mimic upload -->
  <button class="button" id="upload-btn" disabled>Upload</button>
</div>

Leave a comment