简体   繁体   English

使用ajax将多个文件附件发送到php文件

[英]Send multiple file attachments to php file using ajax

I have the following html code inside a form: 我在表单中有以下html代码:

<input type="file" id="attachments" name="attachments" multiple>

I already have a javascript function that handles the onsubmit for the form using ajax but without handling the uploaded files. 我已经有一个javascript函数,使用ajax处理表单的onsubmit,但不处理上传的文件。

This is the part of my javascript function that sends the data to the required php file: 这是我的javascript函数的一部分,它将数据发送到所需的php文件:

var to_users = $("#to_users").val();            
var title = $("#title").val();
var content = $("#content").val();

var data = {
    to_users:to_users,
    title:title,
    content:content
}

$.ajax({url: "submit.php", type:"POST" , data:data ,success: function(result){

    // does something
}});

There are many tutorials and questions online about attachments using ajax and php but none of them handles multiple files. 关于使用ajax和php的附件在线有许多教程和问题,但没有一个处理多个文件。 My question is: what do I need to add to this function so that I send the attached files to the php file ? 我的问题是:我需要添加到这个函数,以便将附加的文件发送到php文件? And what should I write in the php file in order to handle the files it receives? 我应该在php文件中写什么来处理它收到的文件?

To upload multiple images use array: 要上传多个图像,请使用数组:

<input type="file" id="attachments" name="attachments[]" multiple>

and send the form data using ajax: 并使用ajax发送表单数据:

 var formData = new FormData(this);
$.ajax({
    url: "submit.php",
    type: "POST",
    data: formData,
    processData: false,
    contentType: false,
    success: function(result){

    // do something
   }
});

In php file use a loop( foreach i recommend) to save all attachments. 在php文件中使用循环( foreach i recommended)来保存所有附件。

foreach($_FILES['attachments']['name'] as $key=>$val){

// do whatever you want

}

There are quite a lot of questions that are almost duplicates, but they all suffer from creating a FormData object and then adding fields to it one-by-one … which fails to show how to handle multiple file inputs (and is a long-winded and fragile approach to the problem). 有很多问题几乎都是重复的,但它们都会受到创建FormData对象,然后逐个添加字段......这无法显示如何处理多个文件输入(并且是一个冗长的问题)和脆弱的问题解决方法)。

Just pass the form element as the argument to the FormData object instead. 只需将form元素作为参数传递给FormData对象。

var formData = new FormData(document.querySelector("form"));
$.ajax({
    url: "submit.php",
    type: "POST",
    data: formData,
    processData: false,
    contentType: false
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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