使用ajax发送多个文件附件到php文件 [英] Send multiple file attachments to php file using ajax

查看:142
本文介绍了使用ajax发送多个文件附件到php文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < input type =fileid =attachments name =attachmentsmultiple> 

我已经有了一个javascript函数来处理表单的onsubmit,但是没有处理上传的文件。



这是我的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
}});

有许多关于使用ajax和php的附件的教程和问题,但是它们都没有处理多个文件。
我的问题是:我需要添加什么功能,以便将附件发送到php文件?为了处理它接收到的文件,我应该在php文件中写入什么?为了上传多个图像,使用数组:

 < input type =fileid =attachmentsname =attachments []multiple> 

并使用ajax发送表单数据:

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

//做某事
}
});

在php文件中使用循环( foreach



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

//做任何你想做的事

}


I have the following html code inside a form:

<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.

This is the part of my javascript function that sends the data to the required php file:

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. My question is: what do I need to add to this function so that I send the attached files to the php file ? And what should I write in the php file in order to handle the files it receives?

解决方案

To upload multiple images use array:

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

and send the form data using 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.

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

// do whatever you want

}

这篇关于使用ajax发送多个文件附件到php文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆