Search code examples
phpajaxcodeigniter

upload multiple images files using ajax and php in CodeIgniter


I had a problem uploading multiple image files to the server side. It would be good if someone could highlight what's is the problem with the code.

Initially had HTML code :

<label class="col-form-label"><h4>Upload Images</h4></label>
              <div id="image-preview-container">
                <!-- Preview images will be displayed here -->
              </div>
              <form id="uploadCert" enctype="multipart/form-data">
                <input type="file" id="images" name="images" multiple="multiple" accept="image/*" style="display: none;">
                <label for="images" class="btn btn-primary"> Add Image </label>
              </form>
            </div>

At javascript defined

var selectedImages = []; //list of files in array

and capture each selected file at

$("#images").change(function () {
  var file = this.files[0];

  if (file) {
    ...

    // Append the container to the image preview container
    $("#image-preview-container").append(imageContainer);

    ..

    // Add the selected image file to the postData.images array
    selectedImages.push(file);
    
    $(this).val("");
  }
});

at AJAX upon submit

$('#addcart').click(function () {

        // Add other form fields to formData
        var formData = new FormData();
        ...
        formData.append("issuesBody", $("#fbody_").val());
        ...
        
        if (selectedImages.length > 0) {
            // Append each selected image to formData
            for (var i = 0; i < selectedImages.length; i++) {
                var image = selectedImages[i];
                if (image instanceof File) {
                  // If it's a File object, append it to formData
                  formData.append("images[]", image);

                }
            }
        } else {
            // If no selected images, set images[] to an empty array
            formData.append("images[]", []);
        }

        // Make the AJAX request
        event.preventDefault();
        $.ajax({
            url: "addcert",
            type: "POST",
            data: formData,
            dataType:"json",
            contentType:false,
            cache:false,
            processData: false,
            success: function(data){
                // Handle a successful response
                ...
            },
            error: function (xhr, status, error) {
                // Handle an error response
                ...
            }
        });

     });


});

at PHP

private function addNewCert(){
        // Capture POST data
        $issuesBody = $this->input->post('issuesBody'); 
        // Not sure if this is the way to capture the posted file data
        $images = $_FILES['images']; 

        // Upload images to the server
        $uploadedFiles = $this->uploadimg($images);

        //Check if image uploads were successful
        if ($uploadedFiles === false) {
            // Handle the case where image uploads failed
            ...
            echo json_encode($output);
            return;
        } ...

Finally during uploadimg() always shows 'undefined' and here the code

private function uploadimg($images) {
        $uploadedFiles = array(); // captured uploaded file name

        // Loop through each uploaded file
        for ($i = 0; $i < count($images['name']); $i++) {
            // Generate a unique file name or use the original name
            $originalFileName = $images['name'][$i];
            $fileExtension = pathinfo($originalFileName, PATHINFO_EXTENSION);
            $file_name = uniqid() . '_' . $originalFileName;

            $config['upload_path'] = $this->uploadPath;
            $config['file_name'] = $file_name;
            $config['allowed_types'] = 'jpg|jpeg|png|gif'; 
            $config['max_size'] = 2048; 
            $config['encrypt_name'] = TRUE; 

            $this->load->library('upload', $config);

            // Perform the upload
            if ($this->upload->do_upload('images')) {
                $uploadedFiles[] = $file_name;
            } else {
                // Handle the case where an upload failed
                return false;
            }
        }

        return $uploadedFiles;
    }

Solution

  • There are actually, more than one issues in the code. Firstly, you should take the $this->load->library('upload',$config) statement out of the for loop. And you need to create kind of single files from each file in the list in order to upload. Codeigniter do_upload method doesn't work with multiple files, if I am not mistaken. You can renew your uploadimg method like below:

    private function uploadimg($images) {
        $uploadedFiles = array(); // captured uploaded file name
    
        $config = [
            'upload_path' => './testUploads/',
            'allowed_types' => 'jpg|jpeg|png|gif',
            'max_size' => 2048,
            'encrypt_name' => TRUE,
        ];
        $this->load->library('upload', $config);
    
        // Loop through each uploaded file
        for ($i = 0; $i < count($images['name']); $i++) {
            // Generate a unique file name or use the original name
            $originalFileName = $images['name'][$i];
            $fileExtension = pathinfo($originalFileName, PATHINFO_EXTENSION);
            $file_name = uniqid() . '_' . $originalFileName;
    
            $config['file_name'] = $file_name;
            $this->upload->initialize($config);
    
            $_FILES['singleImage']['name']     = $file_name;
            $_FILES['singleImage']['type']     = $images['type'][$i];
            $_FILES['singleImage']['tmp_name'] = $images['tmp_name'][$i];
            $_FILES['singleImage']['error']    = $images['error'][$i];
            $_FILES['singleImage']['size']     = $images['size'][$i];
            
    
            // Perform the upload
            if ($this->upload->do_upload('singleImage')) {
                $uploadedFiles[] = $file_name;
            } else {
                // Handle the case where an upload failed
                return false;
            }
        }
    
        return $uploadedFiles;
    }
    

    P.S I see, you are generating a more readable file name. If you want to find your files with that naming structure, you should set false for encrypt_name field in config array.