简体   繁体   中英

cancel button cannot be clicked after file select (form submission)

I have a very simple html page which has a file upload button as well as a modal popup to show loading status and a cancel button. My problem is that the cancel button seems to be blocked while it's processing the file (making it useless). How can I have a button which will cancel the form submission.

HTML:

<body>
    <div id="myModal" class="modal">
        <div class="modal-content">
            <p>Processing File.</p>
            <div class="loader-inner pacman"><div></div><div></div><div></div><div></div><div></div></div>
            <div id="progressbar" ></div>
            <input type = "button" name="cancel" value = "cancel" onclick = "cancelRead()" />
        </div>
    </div>

    <div>
        <input type="file" id="logSelector" name="log" title="Select a log file" onchange="logSelected();"/>

JS:

function cancelRead() {
    console.log("cancelRead");  //never see this message even though the button is clicked
    fileReader.abort();
    operationAborted = true;
    document.execCommand('Stop');
}

The logSelected() method is quite lengthy and I omitted it from the above code mostly to eliminate clutter. That method uses FileReader to read the selected file than create a table from the data. However I do signal to this method to stop via the operationAborted variable. however like i said in the comments, this method is never called by clicking my button. The cancel button doesnt even animate like it was clicked.

The promise api was mentioned below, here is my attempt at it. Although it works it did not fix the issue of the cancel button not clickable due to the main/only thread being used.

var promise = $.Deferred(function (dfd) {
    FILE_READER.onload = function (event) {
        var contents = event.target.result;
        dfd.resolve(contents);
    };
    FILE_READER.readAsText(file);
}).promise();
$.when(promise).then(function (contents) {
    processFile(contents.split('\n'));
});

而且由于事件循环在javascript浏览器中的工作原理,几乎可以肯定它永远不会起作用。

This could be because the file reader is using up all of the thread leaving to time to process the function to be called - you see, JavaScript only has one thread & thus can only handle one thing at a time, & this one thing is the file reader!


edit
However you could use a promise (as explained here ) to run the file reader asynchronously & cancel the promise.
I don;t have much experience with using promises so I can't give much advice, but it is worth a look.

You page remain blocked until this thead (uploading the file) its done. Since its a blocking function, your user won't be able to do anything until this task end.

Your alternative is to use non-block io

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