html5 ajax上传附件,HTML5多文件上传:通过AJAX逐个上传

这篇博客探讨了如何使用AJAX进行文件上传,特别是如何实现同步操作,确保所有内容同时发送,如Gmail所做。通过监听'progress'事件和XMLHttpRequest2,可以实现文件上传进度的跟踪。示例代码展示了如何处理多文件上传,并在每个文件上传成功后触发下一次上传。注意,这种方法仅适用于支持FormData和XmlHttpRequest2的现代浏览器。
摘要由CSDN通过智能技术生成

pocesar..

31

要使其成为同步操作,您需要在完成最后一次操作时启动新传输.例如,Gmail会同时发送所有内容.对AJAX的文件上传进度的事件progress或onprogress对原始XmlHttpRequest实例.

因此,在$.ajax()服务器端(我不知道你将使用什么)之后,发送一个JSON响应以在下一个输入上执行AJAX.一种选择是对AJAX元素结合到每一个元素,使事情变得更容易,所以你可以只是做在success了$(this).sibling('input').execute_ajax().

像这样的东西:

$('input[type="file"]').on('ajax', function(){

var $this = $(this);

$.ajax({

'type':'POST',

'data': (new FormData()).append('file', this.files[0]),

'contentType': false,

'processData': false,

'xhr': function() {

var xhr = $.ajaxSettings.xhr();

if(xhr.upload){

xhr.upload.addEventListener('progress', progressbar, false);

}

return xhr;

},

'success': function(){

$this.siblings('input[type="file"]:eq(0)').trigger('ajax');

$this.remove(); // remove the field so the next call won't resend the same field

}

});

}).trigger('ajax'); // Execute only the first input[multiple] AJAX, we aren't using $.each

上面的代码是多个但不是,在这种情况下,它应该是:

var count = 0;

$('input[type="file"]').on('ajax', function(){

var $this = $(this);

if (typeof this.files[count] === 'undefined') { return false; }

$.ajax({

'type':'POST',

'data': (new FormData()).append('file', this.files[count]),

'contentType': false,

'processData': false,

'xhr': function() {

var xhr = $.ajaxSettings.xhr();

if(xhr.upload){

xhr.upload.addEventListener('progress', progressbar, false);

}

return xhr;

},

'success': function(){

count++;

$this.trigger('ajax');

}

});

}).trigger('ajax'); // Execute only the first input[multiple] AJAX, we aren't using $.each

创建一个新的'表单'并使用`(new FormData())逐个添加文件.append('file',this.files [count])`就是我想要的,谢谢! (5认同)

请注意,此代码仅适用于仅支持FormData和XmlHttpRequest2的现代浏览器,不适用于旧版浏览器 (4认同)

想知道它为什么看起来那么美味......;) (4认同)

网址在哪里? (2认同)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值