0

I want to uplod multiple files through ajax but I can't figure out how I can grab the files in PHP. Can anyone help me? Thank you! Here is the code:

HTML:

<form  enctype="multipart/form-data" method="POST">
    <input type="file" id="file" multiple="multiple" name="file"/>
</form>
<div id="info"></div>
<div id="preview"></div>

JavaScript:

$(document).ready(function(){
    $("#file").change(function(){

        var src=$("#file").val();
        if(src!="")
        {
            formdata= new FormData();  // initialize formdata
            var numfiles=this.files.length;  // number of files
            var i, file, progress, size;
            for(i=0;i<numfiles;i++)
            {
                file = this.files[i];
                size = this.files[i].size;
                name = this.files[i].name;
                if (!!file.type.match(/image.*/))  // Verify image file or not
                {
                    if((Math.round(size))<=(1024*1024)) //Limited size 1 MB
                    {
                        var reader = new FileReader();  // initialize filereader
                        reader.readAsDataURL(file);  // read image file to display before upload
                        $("#preview").show();
                        $('#preview').html("");
                        reader.onloadend = function(e){
                            var image = $('<img>').attr('src',e.target.result);
                            $(image).appendTo('#preview');
                        };
                        formdata.append("file[]", file);  // adding file to formdata
                        console.log(formdata);
                        if(i==(numfiles-1))
                        {
                            $("#info").html("wait a moment to complete upload");
                            $.ajax({

                                url: _url + "?module=ProductManagement&action=multiplePhotoUpload",
                                type: "POST",
                                data: formdata,
                                processData: false,
                                contentType: false,
                                success: function(res){
                                    if(res!="0")
                                        $("#info").html("Successfully Uploaded");
                                    else
                                        $("#info").html("Error in upload. Retry");
                                }
                            });
                        }
                    }
                    else
                    {
                        $("#info").html(name+"Size limit exceeded");
                        $("#preview").hide();
                        return;
                    }
                }
                else
                {
                    $("#info").html(name+"Not image file");
                    $("#preview").hide();
                    return;
                }
            }
        }
        else
        {
            $("#info").html("Select an image file");
            $("#preview").hide();
            return;
        }
        return false;
    });
});

And in PHP I get $_POST and $_FILES as an empty array; Only if I do file_get_contents("php://input"); I get something like

-----------------------------89254151319921744961145854436
Content-Disposition: form-data; name="file[]"; filename="dasha.png"
Content-Type: image/png

PNG

���
IHDR��Ò��¾���gǺ¨���    pHYs��������tIMEÞ/§ýZ�� �IDATxÚìw`EÆgv¯¥B-4 ½Ò»tBU©)"¶+*"( E¥J7ôÞ;Ò¤W©¡&puwçûce³WR¸ èóûrw»³ï}fö

But I can't figure out how to proceed from here.

I am using Jquery 1.3.2 maybe this is the problem?

Thank you!

1
  • try to use name as a array. like file[] Commented Sep 11, 2014 at 10:56

3 Answers 3

1

Sorry about the answer, but I can't add a comment yet.

I would recommend not checking the file type in javascript, it is easily bypassed. I prefer to scrutinise the file in PHP before allowing it to be uploaded to a server.

e.g.

This answer taken from another question (uploaded file type check by PHP), gives you an idea:

https://stackoverflow.com/a/6755263/1720515

<?php
$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$detectedType = exif_imagetype($_FILES['fupload']['tmp_name']);
$error = !in_array($detectedType, $allowedTypes);
?>

You can read the documentation on the exif_imagetype() function here.

Could you post your PHP code please? And I will update my answer if I have anything to add.

UPDATE:

NOTE: The 'multiple' attribute (multiple="multiple") cannot be used with an <input type='file' /> field. Multiple <input type='file' /> fields will have to be used in the form, naming each field the same with [] added to the end to make sure that the contents of each field are added to an array, and do not overwrite each other when the form is posted.

e.g.

<form  enctype="multipart/form-data" method="POST">
  <input type="file" id="file_0" name="img_file[]" />
  <input type="file" id="file_1" name="img_file[]" />
  <input type="file" id="file_2" name="img_file[]" />
</form>

When the form is submitted, the contents of any <input type='file' /> fields will be added to the PHP $_FILES array. The files can then be referenced using $_FILES['img_file'][*parameter*][*i*], where 'i' is key associated with the file input and 'paramter' is one of a number of parameters associated with each element of the $_FILES array:

e.g.

  • $_FILES['img_file']['tmp_name'][0] - when the form is submitted a temporary file is created on the server, this element contains the 'tmp_name' that is generated for the file.
  • $_FILES['img_file']['name'][0] - contains the file name including the file extension.
  • $_FILES['img_file']['size'][0] - contains the file size.

$_FILES['img_file']['tmp_name'][0] can be used to preview the files before it is permanently uploaded to the server (looking at your code, this is a feature you want to include)

The file must then be moved to its permanent location on the server using PHP's move_uploaded_file() function.

Here is some example code:

<?php
  if (!empty($_FILES)) {
    foreach ($_FILES['img_file']['tmp_name'] as $file_key => $file_val) {
      /*
        ...perform checks on file here

        e.g. Check file size is within your desired limits,
             Check file type is an image before proceeding, etc.
      */

      $permanent_filename = $_FILES['img_file']['name'][$file_key];

      if (@move_uploaded_file($file_val, 'upload_dir/' . $permanent_filename)) {
        // Successful upload
      } else {
        // Catch any errors 
      }
    }
  }
?>

Here are some links that may help with your understanding:

Plus, some extra reading concerning the theory around securing file upload vulnerabilities:

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

4 Comments

About the PHP code I cant post any thing because I can't figure out how to grab the data and to process it only thing I have a input $file = file_get_contents("php://input"); print_r($file);
I am aware how to upload a file on the server but the main problem that i encounter is that I am trying to do that with ajax. At the moment a simple var_dump of the globals $_FILES and $_POST returns emppty. the only way I get something in return is by using $file = file_get_contents("php://input"); but i dont know how to proceed from this. Thank you James for the answers!
So the PHP file that you are posting to (_url + "?module=ProductManagement&action=multiplePhotoUpload") only contains $file = file_get_contents("php://input"); print_r($file);?
yes, and a simple var_dump shows in the console a string o characters like I showed above.
1

You can use ajax form upload plugin

That's what i have found couple of days ago and implemented it this way
Ref : LINK

You PHP Code can be like this

uploadimage.php

    $response = array();
    foreach ($_FILES as $file) {
        /* Function for moving file to a location and get it's URL */
        $response[] = FileUploader::uploadImage($file);
    }
    echo json_encode($response);

JS Code

      options = {
                beforeSend: function()
                {
                    // Do some image loading
                },
                uploadProgress: function(event, position, total, percentComplete)
                {
                    // Do some upload progresss
                },
                success: function()
                {
                    // After Success
                },
                complete: function(response)
                {
                    // Stop Loading
                },
                error: function()
                {

                }

            };

            $("#form").ajaxForm(options);

Now you can call any AJAX and submit your form.

Comments

0

You should consider below code

HTML

   <input type="file" name="fileUpload" multiple>

AJAX

  • first of all you have to get all the files which you choose in "input type file" like this.

            var file_data = $('input[type="file"]')[0].files;
            var form_data = new FormData();
    
            for(var i=0;i<file_data.length;i++)
            {
    
                form_data.append(file_data[i]['name'], file_data[i]);
            }
    
  • then all your data is in formData object now you can send it to server(php) like this.

            $.ajax({
                url: 'upload.php', //your php action page name
                dataType: 'json', 
                contentType: false,
                processData: false,
                data: form_data,
                type: 'post',
                success: function (result) {
                  // code you want to execute on success of ajax request
                },
                error: function (result) {
                  //code you want to execute on failure of ajax request
                }
            });
    

    PHP

    <?php
    
    foreach($_FILES as $key=>$value)
    {
     move_uploaded_file($_FILES[$key]['tmp_name'], 'uploads/' .$_FILES[$key]['name']);
    
    }
    

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.