如何.abort()ajax文件上传?

时间:2022-08-25 16:26:21

I'm experimenting with ajax-based file uploading following this article, and so far the process is working fine, but I've been unable to find how I could implement an abort button for the file list.

我正在尝试在本文之后进行基于ajax的文件上传,到目前为止,该过程工作正常,但我一直无法找到如何为文件列表实现中止按钮。

The core code in the article is this:

本文的核心代码是:

var fileInput = document.getElementById('the-file');
var file = fileInput.files[0];

var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', onprogressHandler, false);
xhr.open('POST', '/upload/uri', true);
xhr.send(file);

function onprogressHandler(evt) {
    var percent = event.loaded/event.total*100;
    console.log('Upload progress: ' + percent + '%');
}

The article mentions that it is possible to define an abort listener:

文章提到可以定义一个中止监听器:

xhr.upload.onabort = function (evt) {
    console.log("Aborted", evt);
}

According to MDC there's an abort method in the FileReader object, but it is unclear to me how I should use it in this case (or if it is the same "abort" that I'm looking for at all).

根据MDC,在FileReader对象中有一个中止方法,但我不清楚在这种情况下我应该如何使用它(或者如果它与我正在寻找的相同的“中止”)。

What I'd like to have is an abort button next to each file selected for uploading, and if the user clicks a button then that file should be removed from the list or if its uploading has been started it should be immediately aborted.

我想要的是每个选择上传的文件旁边的中止按钮,如果用户单击一个按钮,那么该文件应该从列表中删除,或者如果上传已经开始,则应立即中止。

1 个解决方案

#1


7  

There is an abort method on the XMLHttpRequest object. You can do the following: xhr.abort() and that should abort the request.

XMLHttpRequest对象上有一个abort方法。您可以执行以下操作:xhr.abort(),这应该中止请求。

#1


7  

There is an abort method on the XMLHttpRequest object. You can do the following: xhr.abort() and that should abort the request.

XMLHttpRequest对象上有一个abort方法。您可以执行以下操作:xhr.abort(),这应该中止请求。