XHR abort doesn't stop file uploading

后端 未结 3 858
鱼传尺愫
鱼传尺愫 2020-12-20 06:14

I\'ve made an XHR-based file uploader with progressbar, and I would like to add a feature to cancel the upload before it fully uploaded. The simlified code (runs after DOM r

相关标签:
3条回答
  • 2020-12-20 06:55

    Ok, I noticed that the event name is onabort. With the xhr.abort = ... line I overwrote the abort function. So the solution:

    xhr.onabort = function(){...};

    or

    xhr.addEventListener("abort", function(){...});

    0 讨论(0)
  • 2020-12-20 06:59

    I have been scouring the forums and found many solutions that fail miserably...except for Ivan Tsai's response.

    The abort method will trigger error handlers on the server and the request object's abort event, but it will not stop the upload.

    I have had no success stopping the upload from the server upon receiving the abort event. The following all fail:

    request.pause();
    request.socket.end();
    request.connection.end();
    request.destroy();
    
    response.status(413).send(message);
    response.end();
    

    The only effective way I have found to stop the upload below is the HTMLFormElement.reset() method. Interestingly, calling the reset method of an input of type file will not work, but the single input can be wrapped in a singleton form element, such as the uploadForm below, to achieve the desired effect.

    var formData = new FormData(uploadForm),
        files = fileInput.files,
        xhr;
    
    if(files) {
       for (var i = 0, stop = files.length; i < stop; i++) {
           formData.append(files[i].name, files[i]);
       }
    
       xhr = new XMLHttpRequest();
       xhr.open('POST', uploadForm.getAttribute('action'), true);
       progressListener = xhr.upload.addEventListener("progress", progressHandler, true);
       xhr.upload.addEventListener("abort", abortHandler, true);
       xhr.send(formData);
    }
    
    abortButton.addEventListener(function(){
        if(xhr){
            xhr.abort();
        }
        uploadForm.reset();
    });
    
    0 讨论(0)
  • 2020-12-20 07:07

    I have the same problem.

    XMLHttpRequest.abort() just stop notifying XMLHttpRequest.uplad.progress.

    XMLHttpRequest.abort() can't stop Chrome(63.0.3239.132) uploading files.

    I tried the formObject.reset() with upload 1G file and it works.

    Network usage in windows task manager goes down to zero after calling formObject.reset().

    <script>
    function cancelUploadFile() {
      document.getElementById("my_form").reset();
    }
    </script>
    
    <form id="my_form" method="post" enctype="multipart/form-data">
      <div class="w3-grey"  style="height:24px;width:0%" hidden 
    id="progressBar"></div>
      <input type="file" id="file1" name="file1">
      <input type="submit" value="Upload" onclick="uploadFile()">
      <input type="submit" value="Cancel" onclick="cancelUploadFile()">
    </form>
    0 讨论(0)
提交回复
热议问题