0

I want to handle the cancel press when uploading a file

enter image description here

I looked at some examples that were implemented using pure JavaScript here is an example

All these examples work fine, I tried to implement this example using Vue JS, but it does not work correctly for me

<div>
   <label for="upload" @click="initialize">Upload File</label>
   <input type="file" id="upload" ref="theFile" hidden />
</div>

<script>
export default {
  methods: {
    initialize() {
      document.body.onfocus = this.checkIt;
      alert("initializing");
    },

    checkIt() {
      if (this.$refs.theFile.value.length) alert("Files Loaded");
      else alert("Cancel clicked");
      document.body.onfocus = null;
      alert("checked");
    },
  },
};
</script>

You can see an example of my code in codesandbox

isherwood
  • 58,414
  • 16
  • 114
  • 157
Synchro
  • 1,105
  • 3
  • 14
  • 44
  • Protip: use something other than alerts. [They should be avoided](https://ux.stackexchange.com/questions/4518/should-alert-boxes-be-avoided-at-any-cost). – isherwood Feb 03 '22 at 14:34
  • afaik there's no event you can use for that. what is the use case? relevant question: https://stackoverflow.com/q/34855400/10975709 – captainskippah Feb 03 '22 at 14:40

1 Answers1

1

As stated in the comments, there isn't an event to capture canceling and you would be better off just adding a submit button.

Having said that, this will tell you if files were uploaded when the next 'mouseenter' event is fired on the body. It won't tell you if the cancel button was clicked.

<template>
  <form>
    <label for="upload">Upload File</label>
    <input
      @click="onShowFileUpload"
      @change="onFileUpload"
      type="file"
      id="upload"
      ref="theFile"
      hidden
    />
  </form>
</template>

<script>
export default {
  methods: {
    onShowFileUpload() {
      this.$refs.theFile.value = "";
      const onHandleMouseEnter = () => {
        if (this.$refs.theFile.value.length === 0) {
          console.log("No files loaded");
        }
        document.body.removeEventListener("mouseenter", onHandleMouseEnter);
      };
      document.body.addEventListener("mouseenter", onHandleMouseEnter);
    },
    onFileUpload(event) {
      console.log("Files Uploaded");
    },
  },
};
</script>
<style>
html,
body {
  height: 100%;
  height: 100%;
}

label {
  font-family: sans-serif;
  font-size: 20px;
  border: 1px solid tomato;
  padding: 7px 15px;
  cursor: pointer;
}
</style>
first last
  • 396
  • 2
  • 5
  • this might not work in some cases where keyboard navigation was used. point is, if you have something **important** to do, don't rely on hacks like this and you might be approaching the problem the wrong way. if not, then you're fine. – captainskippah Feb 04 '22 at 03:26
  • You are right, I just discovered this problem today that you highlighted – Synchro Feb 04 '22 at 07:29