简体   繁体   中英

event for file upload cancel in javascript

We can use file.onchange if we gonna set an event callback for file reading using javascript, but how to set event for when user cancel the upload (close the browse panel)?

There is no API for the file input modal. Besides, if the user closes the browser your code won't be running anymore, will it?

Of course there is the window.onunload method which allows you to detect the example you give.

Per the comments, the best thing I can come up with that would be helpful is that if nothing is selected, file.value.length will be 0 .

That's a great solution:

    const createUpload = () => {
        let lock = false
        return new Promise((resolve, reject) => {
            const el = document.createElement('input');
            el.id = +new Date();
            el.style.display = 'none';
            el.setAttribute('type', 'file');
            document.body.appendChild(el)

            el.addEventListener('change', () => {
                lock = true;
                const file = el.files[0];
                resolve(file)
                document.body.removeChild(document.getElementById(el.id));
            }, { once: true })

            window.addEventListener('focus', () => { // file blur
                setTimeout(() => {
                    if (!lock && document.getElementById(el.id)) {
                        reject(new Error('onblur'))
                        document.body.removeChild(document.getElementById(el.id))
                    }
                }, 300)
            }, { once: true })
            el.click() // open file select box
        })
    }

Ussage:

    // $label.classList.add('loading');
    createUpload()
        .then(function (file) {
            // Sent file 
            // $label.classList.remove('loading');           
        })
        .catch(function (err) {
            // Your Cancel Event
            // $label.classList.remove('loading');
        });

It is very simple with jQuery :

$("#fileInputId").change(function () {
    //implement your code here
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM