简体   繁体   English

javascript 中的文件上传取消事件

[英]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)?如果我们要使用 javascript 为文件读取设置事件回调,我们可以使用file.onchange ,但是当用户取消上传(关闭浏览面板)时如何设置事件?

There is no API for the file input modal. 文件输入模式没有API。 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. 当然有window.onunload方法,它允许您检测您给出的示例。

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 . 根据评论,我能想出的最好的事情是有用的是,如果没有选择任何内容, file.value.length将为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 : 使用jQuery非常简单:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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