简体   繁体   中英

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

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

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.

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

example on jsfiddle

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)

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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