4

Hey I am uploading files to a chosen folder and right now I have the ability to select and upload just one file. I know how to handle multiple files in php but I am not sure how to send all of the files over through AJAX. Thanks for any help you can offer

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";
}
?>
4
  • Is the element returned from this document.getElementById("fileinfo") a form? If not, it should be. Commented Jan 29, 2016 at 13:50
  • Here fileinfo is id of the form right? It should. Commented Jan 29, 2016 at 13:53
  • Nick Did you try with answer? Commented Jan 29, 2016 at 14:16
  • wow thanks guys this is perfect! i am in calc class right now but i will definitely try this when i get home. I have a php file that would work perfectly with this. Commented Jan 29, 2016 at 14:17

2 Answers 2

3

You can pass multiple files using form data as below

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");                    
    }        
 })

Now pass fd object in you ajax call it is working with my code

Sign up to request clarification or add additional context in comments.

4 Comments

didi you have a php example that i would be able to run next to this?
@NickGarver Sorry but I don't have pretty much knowledge of PHP I can do this with Asp.net.
Thanks you for your code, I have implemented the ajax inside the loop. so how can I clear form data before append the new file?
@Samphors I could not understood what you exactly want to do
3

First you have to use "multiple" attribute with input tag. Like

<input id="fileUpload" type="file" accept="image/*" name="my_file[]" multiple />

Then in Javascript onChange function -

        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!")
        });

And your file will be uploaded

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.