javascript 如何通过单击“取消”按钮取消文件上传

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10153916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:51:38  来源:igfitidea点击:

How to cancel a file upload by clicking on a 'Cancel' button

javascriptjquerybuttonfile-upload

提问by user1333290

I have a form which contains a file input within the form and more importantly a cancel button which should cancel a file upload:

我有一个表单,其中包含表单中的文件输入,更重要的是一个取消按钮,它应该取消文件上传:

var $fileImage = $("<form action='imageupload.php' method='post' class='imageuploadform' ...><label>" + 

"Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><label>" +

"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" + 

"</p><p class='imagef1_cancel' align='center'><label>" +

"<input type='button' name='cancelImageBtn' class='cancelimage' value='Cancel' /></label>" + 
"</p></form>");

Now I have completed everything when it comes to uploading a file into a server and all that. But I have one problem.

现在我已经完成了将文件上传到服务器的所有工作。但我有一个问题。

The problem I have is that I do not know how to cancel and upload. At the moment if the user clicks on the 'Cancel' button, then nothing happens. What I want to happen is that if the user clicks on the "Cancel" button, then it would navigate to the "stopImageUpload()" function and that it stops the file upload. But how can I do this?

我的问题是我不知道如何取消和上传。目前,如果用户单击“取消”按钮,则什么也不会发生。我想要发生的是,如果用户点击“取消”按钮,那么它会导航到“stopImageUpload()”函数并停止文件上传。但是我该怎么做呢?

Below is my attempt to create the cancel button function but when the "Cancel" button is clicked, nothing happens.

下面是我尝试创建取消按钮功能,但是当单击“取消”按钮时,没有任何反应。

   $(".cancelimage").on("click", function(event) {
    console.log("clicked");
    event.preventDefault();
    stopImageUpload(success);
     });

Below is the full code which shows where the cancel button function is placed and the functions which starts the uploading and stops the uploading of the files:

下面是完整代码,显示了取消按钮功能的位置以及开始上传和停止上传文件的功能:

          function startImageUpload(imageuploadform){

$(imageuploadform).find('.imagef1_upload_process').css('visibility','visible');
sourceImageForm = imageuploadform;

                $(".cancelimage").on("click", function(event) {
                console.log("clicked");
                event.preventDefault();
                stopImageUpload(success);
             });

                  return true;
            }

            function stopImageUpload(success){

                  var result = '';
                  if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
                  }

                  else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
                  }

$(sourceImageForm).find('.imagef1_upload_process').css('visibility','hidden');          
$(sourceImageForm).find('.imagef1_upload_form').css('visibility','visible');


                  return true;   
            }

回答by Chinbold Gansukh

There is a possible solution. You can do like that:

有一个可能的解决方案。你可以这样做:

$("#cancel").click(function(){
  $("#inputfile").remove();
  $("#containerof_inputfile").append("<input type=\"file\" id=\"inputfile\"/>");
});

回答by Mohamed Allal

This an answer for people that may lend here. (not answering completly the question as it is already too old)

这是可能借给这里的人的答案。(不完全回答问题,因为它已经太旧了)

I will answer how you can implement cancel upload, or more cancel ajax request. Which can be needed in a lot of applications.

我将回答您如何实现取消上传或更多取消 ajax 请求。在许多应用程序中都可能需要它。

Using axios

使用 axios

You can cancel a request using a cancel token.

您可以使用取消令牌取消请求。

The axios cancel token API is based on the withdrawn cancelable promises proposal.

axios 取消令牌 API 基于已撤销的可取消承诺提案。

You can create a cancel token using the CancelToken.source factory as shown below:

您可以使用 CancelToken.source 工厂创建取消令牌,如下所示:

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function (thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

And to trigger the cancel

并触发取消

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');

You can also create a cancel token by passing an executor function to the CancelToken constructor:

您还可以通过将执行器函数传递给 CancelToken 构造函数来创建取消令牌:

const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request
cancel();

Note: you can cancel several requests with the same cancel token.

doc https://github.com/axios/axios#cancellation

文档https://github.com/axios/axios#cancellation

Using XMLHttpRequest:

使用 XMLHttpRequest:

We use abort()method of the xhr object.

我们使用xhr 对象的abort()方法。

var xhr = new XMLHttpRequest(),
    method = "GET",
    url = "https://developer.mozilla.org/";
xhr.open(method, url, true);

xhr.send();

if (OH_NOES_WE_NEED_TO_CANCEL_RIGHT_NOW_OR_ELSE) {
  xhr.abort();
}

doc https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/abort

doc https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/abort

回答by rastating

Once the form has begun submission I don't believe you can stop it without navigating to a new page.

一旦表单开始提交,我不相信您可以在不导航到新页面的情况下停止它。

If you make your cancel button redirect to the same page but with a flag in the query string that you can use to show up a cancellation notice that might do the trick.

如果您将取消按钮重定向到同一页面,但在查询字符串中带有一个标志,您可以使用该标志来显示可能会起作用的取消通知。

回答by stark

jQuery makes this kind of thing easier. You can call abort on a returned jQuery object. I suppose you can look in the jQuery code to see how it does it if you really want to roll your own.

jQuery 使这种事情变得更容易。您可以对返回的 jQuery 对象调用 abort。我想你可以查看 jQuery 代码,看看它是如何做的,如果你真的想推出自己的。

Edit: I got curious and looked it up. Abort is a method of the XMLHttpRequest function in Javascript.

编辑:我很好奇并查了一下。Abort 是 Javascript 中 XMLHttpRequest 函数的一种方法。