18

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.

5 Answers 5

23

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

Sign up to request clarification or add additional context in comments.

4 Comments

its working fine,but the issue is when I upload same files(which have same names) then getting error,is there any chance to handle this.
Yuriy thanks for your help, the error which described above is server side error,nothing do with JS.Though I'm describing the error: when choose same file twice at time then I getting error 500 i,e. Internal server error.
Yuriy,can look at this,if get any idea,let me know please.Thanks
I think PHP likes [], I think MVC likes [0]
2

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

Comments

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

Comments

0

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

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.