user3642988
user3642988

Reputation: 243

ajax - how to upload multiple files

I'm stuck and need your help - I have designed a simple form which allows the user to upload comment text and files to the server. When the form is submitted, the file upload process is handled in 'upload.php' file. It works perfectly fine for uploading only 1 file.

I would like my script to be able upload multiple files with AJAX.

This is what I did so far -

HTML (part of it):

<input type='file' name='file[]' maxlength='1' accept="image/jpg,image/png,image/jpeg,image/gif" />
<input type='file' name='file[]' maxlength='1' accept="image/jpg,image/png,image/jpeg,image/gif" />
<input type='file' name='file[]' maxlength='1' accept="image/jpg,image/png,image/jpeg,image/gif" />

JS

$(function() {
    $(document).on('submit','form',function(e) {
        e.preventDefault(); 

    var $form = $(this);
    var file_data = $form.find('.file-field').prop('files')[0];   
    var form_data = new FormData();       
    form_data.append('act', act);
    form_data.append('comment[text]',  $form.find('.comment-field').val());   
    form_data.append('comment[pageName]',  $form.find('.pagename-field').val());   

    form_data.append('file[]', file_data);



    $.ajax({
           type: "POST",
           url: "ajax/addComment.php",

           dataType: 'text',  
           cache: false,
           contentType: false,
           processData: false,  
           async: false,
           data: form_data,
           success: function(data)
           {
                $("#loader").hide();
                $('#commentsBox'+$form.find('.refid-field').val()).prepend(data);
                 $("form").reset(); 

           }

         });

    return false; 

    });
});

Upvotes: 0

Views: 4688

Answers (3)

A1Gard
A1Gard

Reputation: 4168

This sample with progressbar:

The HTML :

AJAX Image Upload

<form id="image_upload_form" enctype="multipart/form-data" method="post">
    <input type='file' name='file' maxlength='1' id="image1" accept="image/jpg,image/png,image/jpeg,image/gif" /> <br />
    <input type='file' name='file' maxlength='1' id="image2" accept="image/jpg,image/png,image/jpeg,image/gif" /> <br />
    <input type='file' name='file' maxlength='1'  id="image3" accept="image/jpg,image/png,image/jpeg,image/gif" /> <br />


    <br />
    <br />
    <br />

    <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
    <h3 id="status"></h3>
    <p id="loaded_n_total"></p>


    <input type="button" value="Upload File" onclick="uploadFile()">
</form>

Javascript:

    function _(elementID)
    {
        return document.getElementById(elementID);
    }
    function uploadFile()
    {
        var formdata = new FormData();
        var file = _("image1").files[0];
        if (file == 'undefined') {
            alert('file not selected');
            return false;
        }
        formdata.append("file[]", file);

        var file = _("image2").files[0];
        if (file != 'undefined') {

            formdata.append("file[]", file);
        }
        var file = _("image3").files[0];
        if (file != 'undefined') {

            formdata.append("file[]", file);
        }
        var ajax = new XMLHttpRequest();
        ajax.upload.addEventListener("progress", myProgressHandler, false);
        ajax.addEventListener("load", myCompleteHandler, false);
        ajax.addEventListener("error", myErrorHandler, false);
        ajax.addEventListener("abort", myAbortHandler, false);
        ajax.open("POST", "file_upload_parser.php");
        ajax.send(formdata);
    }

    function myProgressHandler(event)
    {
        _("loaded_n_total").innerHTML =
                "Uploaded " + event.loaded + " bytes of " + event.total;
        var percent = (event.loaded / event.total) * 100;
        _("progressBar").value = Math.round(percent);
        _("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
    }
    function myCompleteHandler(event)
    {
        _("status").innerHTML = event.target.responseText;
        _("progressBar").value = 0;
    }
    function myErrorHandler(event)
    {
        _("status").innerHTML = "Upload Failed";
    }
    function myAbortHandler(event)
    {
        _("status").innerHTML = "Upload Aborted";
    }

and php file "file_upload_parser.php":

<pre>
    <?php 

        print_r($_FILES);
    ?>
</pre>

Upvotes: 1

Shawon Kanji
Shawon Kanji

Reputation: 720

Try this code for multiple image file upload.. for html form..

 <form action="" method="post" enctype="multipart/form-data">
    <input type="file" id="file" name="files[]" multiple="multiple" accept="image/*" />
  <input type="submit" value="Upload!" />
</form>

And the PHP code will be..

<?php
$valid_formats = array("jpg", "png", "gif", "bmp");
$max_file_size = 1024*100; //100 kb
$path = "uploads/"; // Upload directory
$count = 0;

if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
    // Loop $_FILES to exeicute all files
    foreach ($_FILES['files']['name'] as $f => $name) {     
        if ($_FILES['files']['error'][$f] == 4) {
            continue; // Skip file if any error found
        }          
        if ($_FILES['files']['error'][$f] == 0) {              
            if ($_FILES['files']['size'][$f] > $max_file_size) {
                $message[] = "$name is too large!.";
                continue; // Skip large files
            }
            elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
                $message[] = "$name is not a valid format";
                continue; // Skip invalid file formats
            }
            else{ // No error found! Move uploaded files 
                if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name))
                $count++; // Number of successfully uploaded file
            }
        }
    }
}
?>

Upvotes: 0

Vishnu Atrai
Vishnu Atrai

Reputation: 2368

You can not upload files using Ajax. You will have to have form attribute enctype="multipart/form-data" and submit the form using normal html request. To avoid the page refresh you can use iframe.

There are jquery plugins like https://blueimp.github.io/jQuery-File-Upload/ integrating with php you can solve your problem

Upvotes: 1

Related Questions