用php上传ajax多文件

嘿我将文件上传到选定的文件夹,现在我可以选择并上传一个文件。 我知道如何处理php中的多个文件,但我不知道如何通过AJAX发送所有文件。 谢谢你尽你所能的帮助

AJAX

function submitForm() { console.log("submit event"); var fd = new FormData(document.getElementById("fileinfo")); fd.append("label", "sound"); fd.append('label', document.getElementById('selected_folder').value); $.ajax({ url: "upload.php", type: "POST", data: fd, enctype: 'multipart/form-data', processData: false, // tell jQuery not to process the data contentType: false // tell jQuery not to set contentType }).done(function( data ) { console.log("PHP Output:"); console.log( data ); alert("upload success!") }); return false; } 

PHP

 <?php if ($_POST["label"]) { $subfolder = $_POST["label"]; } $allowedExts = array("gif", "jpeg", "jpg", "png"); $temp = explode(".", $_FILES["file"]["name"]); $extension = end($temp); if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"]  0) { // echo "Return Code: " . $_FILES["file"]["error"] . "
"; } else { $filename = $_FILES["file"]["name"]; echo "Upload: " . $_FILES["file"]["name"] . "
"; echo "Type: " . $_FILES["file"]["type"] . "
"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB
"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "
"; if (file_exists("uploaded/".$subfolder .'/'. $filename)) { //already exists } else { move_uploaded_file($_FILES["file"]["tmp_name"], "uploaded/".$subfolder .'/'. $filename); // "Stored in: " . "uploaded/".$subfolder .'/'. $filename; } } } else { echo "Invalid file"; } ?>

您可以使用表单数据传递多个文件,如下所示

HTML

  

JS

 var fd = new FormData(); var files = $("#fuDocument").get(0).files; // this is my file input in which We can select multiple files. fd.append("label", "sound"); for (var i = 0; i < files.length; i++) { fd.append("UploadedImage" + i, files[i]); } $.ajax({ type: "POST", url: 'Url', contentType: false, processData: false, data: fd, success: function (e) { alert("success"); } }) 

现在在你的ajax调用中传递fd对象它正在使用我的代码

首先,您必须对输入标记使用“multiple”属性。 喜欢

  

然后在Javascript onChange函数中 –

  var data = new FormData(); var imgData = document.getElementById('fileUpload'); for (var i = 0; i < imgData.files.length; i++) { data.append('my_file[]', imgData.files[i], imgData.files[i].name); } //now call ajax $.ajax({ url: "upload.php", type: "POST", data: data, enctype: 'multipart/form-data', processData: false, // tell jQuery not to process the data contentType: false // tell jQuery not to set contentType }).done(function( data ) { console.log("PHP Output:"); console.log( data ); alert("upload success!") }); 

并且您的文件将被上传