JS:如何使用 FormData(jQuery Ajax) 发送多个文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16496407/
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-08-26 17:14:32  来源:igfitidea点击:

JS:How to send multiple files using FormData(jQuery Ajax)

javascriptjquerymultipartform-data

提问by Mahesh.D

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

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

HTML

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

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

I'm using PHPat server,using HTML attribute namei,e photoonly I'm able to save files,dynamic file names won't be work for me.

PHP在服务器上使用HTML attribute namephoto只有我可以保存文件,动态文件名对我不起作用。

回答by Yuriy

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

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

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

example on jsfiddle

jsfiddle上的例子

回答by Govan

in front end

在前端

<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=""/>
    <button id="btn">btn</button>
</form>
        <script>
            $(function(){
     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);
          $('#btn').on('click',function(){
        $.ajax({
        url:'https://stores-govan.c9users.io/test',
          type:"POST",
          data:ajaxData,
          processData:false,
          contentType:false,
          success:function(){
            },
          crossDomain:true
        })
        })

        })
     });

})
</script>

at the backend (nodejs) add this(using multer)

在后端(nodejs)添加这个(使用multer)

var multer=require('multer')
app.post('/test',upload.array('photo[]',6),function(req ,res,next){
            var images=[]
               if(req.files){
               for(var i=0;i<req.files.length;i++){
               images[i]=req.files[i].filename }
               }
               console.log(images)
        })

回答by Enrique Mingyar Torrez Hinojos

<input type="file" name="Attachment[]" class="form-control TheFiles" />

The previous answer has a little error that was fixed on the next code, and gonna works to send multiple files via ajax:

上一个答案有一个小错误,已在下一个代码中修复,并且可以通过 ajax 发送多个文件:

var formData = new FormData();
        $.each($(".TheFiles"), function (i, obj) {                
            $.each(obj.files, function (j, file) {                    
                formData.append('Attachment[' + i + ']', file); // is the var i against the var j, because the i is incremental the j is ever 0
            });
        });
        formData.append('Destination', Destination); //add more variables that you need
        formData.append('ReplyTo', ReplyTo);//add more variables that you need
        formData.append('Body', Body);//add more variables that you need

optionally just for you can see my ajax config

可选只是为了你可以看到我的 ajax 配置

$.ajax({
             url: 'YourUrl',
            type: 'POST',
            data: formData,
            async: false,
             success: function (data) {
                location.reload();
            },
            complete: function () {
                $(Here).text('Enviado com sucesso');
            },
            error: function (err) {
                alert("N?o deixe nenhum campo vazio");
            },
            cache: false,
            contentType: false,
            processData: false
        }); 

回答by Dalir

Those answers do not work.

这些答案不起作用。

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);//i had to change "i" by "j"
    })
});

回答by Yaovi TCHUISSI

This works fine:

这工作正常:

var data = new FormData();
for( var i = 0, len = document.getElementById('attachment').files.length; i < len; i++ ){
    data.append( "files" + i, document.getElementById('attachment').files[i] );
}