JS:如何使用FormData发送多个文件(jQuery Ajax) [英] JS:How to send multiple files using FormData(jQuery Ajax)

查看:83
本文介绍了JS:如何使用FormData发送多个文件(jQuery Ajax)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的表单中有多个文件上传,使用 FormData 只上传了一个文件,但我选择了多个要上传的文件,以下是代码

In my form multiple file uploads are there,using FormData only one file is uploading ,though I'm selecting more than one file to upload,following is the code

HTML

<form name="uploadImages" method="post" enctype="multipart/form-data">
<input type="file" name="photo[]" value="">
<input type="file" name="photo[]" value="">
<input type="file" name="photo[]" value="">
</form>

JS

     var ajaxData = new FormData();
     ajaxData.append( 'action','uploadImages');
     jQuery.each($("input[name^='photo']")[0].files, function(i, file) {
        ajaxData.append('photo['+i+']', file);
      });
     $.ajax({
        url: URL,
        data: ajaxData,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        dataType:'json',
        success: function(data) {
            if (data.status == 'success') {
                location.reload();
            }
        }
       });

我在服务器上使用 PHP ,使用 HTML属性名称我,e 照片只有我能够保存文件,动态文件名不会是为我工作。

I'm using PHP at server,using HTML attribute name i,e photo only I'm able to save files,dynamic file names won't be work for me.

推荐答案

你在javascript中有错误:你只在一个输入中迭代文件请看看在这个

You have an error in javascript: you're iterating only over files in one input please have a look at this

var ajaxData = new FormData();
ajaxData.append( 'action','uploadImages');
$.each($("input[type=file]"), function(i, obj) {
        $.each(obj.files,function(j, file){
            ajaxData.append('photo['+j+']', file);
        })
});

jsfiddle

这篇关于JS:如何使用FormData发送多个文件(jQuery Ajax)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆