gpt4 book ai didi

php - 使用php的ajax多文件上传

转载 作者:可可西里 更新时间:2023-11-01 00:58:14 24 4
gpt4 key购买 nike

嘿,我正在将文件上传到选定的文件夹,现在我只能选择并上传一个文件。我知道如何在 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"] < (10000*1024))
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
// echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
$filename = $_FILES["file"]["name"];
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";



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

<input id="fuDocument" type="file" accept="image/*" multiple="multiple" />

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 对象,它正在使用我的代码

关于php - 使用php的ajax多文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35086065/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com