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

2

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

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.
You are right, I just discovered this problem today that you highlighted

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.