简体   繁体   English

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

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

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.我想要发生的是,如果用户单击“取消”按钮,那么它将导航到“stopImageUpload()”function 并停止文件上传。 But how can I do this?但是我该怎么做呢?

Below is my attempt to create the cancel button function but when the "Cancel" button is clicked, nothing happens.下面是我尝试创建取消按钮 function 但是当单击“取消”按钮时,没有任何反应。

   $(".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 的位置以及开始上传和停止上传文件的功能:

          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;   
            }

There is a possible solution. 有可能的解决方案。 You can do like that: 您可以这样做:

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

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. 我将回答如何实现取消上传或更多取消Ajax请求。 Which can be needed in a lot of applications. 在许多应用程序中可能需要。

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 doc 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/zh-CN/docs/Web/API/XMLHttpRequest/abort

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. 如果您将“取消”按钮重定向到同一页面,但在查询字符串中带有一个标志,则可以使用该标志来显示可能会达到目的的取消通知。

jQuery makes this kind of thing easier. jQuery使这种事情变得更容易。 You can call abort on a returned jQuery object. 您可以在返回的jQuery对象上调用abort。 I suppose you can look in the jQuery code to see how it does it if you really want to roll your own. 我想如果您真的想自己滚动自己,可以查看jQuery代码以了解它是如何做到的。

Edit: I got curious and looked it up . 编辑:我很好奇, 抬头看 Abort is a method of the XMLHttpRequest function in Javascript. Abort是Javascript中XMLHttpRequest函数的一种方法。

At least in node, you can use AbortController API to abort script initiated calls.至少在节点中,您可以使用AbortController API中止脚本发起的调用。

These calls may also be calls with file upload payloads.这些调用也可能是带有文件上传负载的调用。

const controller = new AbortController();
const signal = controller.signal;

const fetchSite = async () => {
  try {
    const response = await fetch('https://google.com/', { signal });
    const source = await response.json();
    console.log(todo);
  } catch (error) {
    if (error.name === "AbortError") {
      console.log("Operation aborted");
    } else {
      console.error(err);
    }
  }
};

fetchSite();

controller.abort();

More info here: https://blog.logrocket.com/complete-guide-abortcontroller-node-js/更多信息在这里: https://blog.logrocket.com/complete-guide-abortcontroller-node-js/

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

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