微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用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"] < (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对象与我的代码一起工作

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐