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

匿名 (未验证) 提交于 2019-12-03 02:06:01

问题:

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

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.

回答1:

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



回答2:

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



回答3:

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


回答4:

in front end

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!