js怎样删除服务器文件夹,javascript-如何在服务器上手动取消XMLHttpRequest文件上传(流)...

我正在使用XMLHttpRequest(级别2)将文件上传到node.js服务器.我在服务器端检查文件流中的有效头.现在,如果流式传输中有任何错误,我想触发取消上传.我的XMLHttpRequest代码非常简单:

var xhr = new XMLHttpRequest();

var file;

$('#file').on('change', function(e) {

file = this.files[0];

file.filename = this.files[0].name;

});

$('#submit').on('click', function(e) {

e.preventDefault();

xhr.open('POST', '/upload', true);

xhr.send(file);

});

在服务器端,我正在通过验证程序将req流传输到文件流中.如果验证时发生任何错误,我希望XMLHttpRequest中止上传.但是,仅发送400作为对请求的响应根本不起作用.我为xhr注册了各种听众,但没有一个被解雇.它似乎根本不在乎400,但仍尝试上传文件.通常,我希望在这种情况下会触发onreadystatechange事件.

我尝试通过发出req.end()来关闭请求,但这似乎有点苛刻,并显示出另一种好奇心.如果这样做,XMLHttpRequest将重试以发送POST请求恰好7次(在Chrome中;在Firefox中为5次;是否在任何地方都有记录?).

编辑:正如保罗建议:

…connection close before receiving any status from the server…

在服务器端,我尝试监听响应的finish事件.

checkedFile.on('error', function (err) {

res.status(400);

res.end();

});

res.on('finish', function () {

req.destroy();

});

但是无论如何它都会重试.我只是不在乎400.

也许还有另一种取消而不破坏请求流的方法?

第二次编辑:可以在不破坏请求流的情况下结束请求:

checkedFile.on('wrong', function (err) {

checkedFile.end();

res.writeHead(400, { 'Connection': 'close' });

res.end();

});

但是XHR仍在重试该请求.

解决方法:

在某些情况下,如果服务器过早关闭连接,则允许客户端重试请求,在您的示例中,Chrome就是这样做的. HTTP 1.1 specification, 8.2.4中定义了此行为:

If an HTTP/1.1 client sends a request which includes a request body, but which does not include an Expect request-header field with the “100-continue” expectation, and if the client is not directly connected to an HTTP/1.1 origin server, and if the client sees the connection close before receiving any status from the server, the client SHOULD retry the request.

如果要取消XMLHttpRequest,则应侦听XHR的errorevent,然后调用其abort() method,这将阻止Chrome重新发送该请求.

标签:node-js,express,xmlhttprequest,stream,javascript

来源: https://codeday.me/bug/20191030/1966078.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值