1

Hello I'm using CodeIgniter 3 to create a form to submit multiple input type=text and type=file. I currently tackling on the uploading file. My major challenge is to have a upload feature that can upload and delete selected file before submitting. I follow the code from Multiple file upload - with 'remove file' link but the problem is that based on my understanding from what they wrote is that they only delete on the appearance not the selected file itself. I do not plan on using plugin.

View

<div class="files float-left ms-5" id="files1">
  <span class="row btn btn-file">
  <input type="file" name="files1" multiple />Browse </span>
  <ul class="fileList ms-5"></ul>
</div>

Image of the input type=file

External JavaScript

var filesToUpload = [];
    
$.fn.fileUploader = function (filesToUpload) {
    this.closest(".files").change(function (evt) {

        for (var i = 0; i < evt.target.files.length; i++) {
            filesToUpload.push(evt.target.files[i]);
        };

        var output = [];

        for (var i = 0, f; f = evt.target.files[i]; i++) {
            var removeLink = "<a class=\"removeFile\" href=\"#\" data-fileid=\"" + i + "\"><i class='far fa-times-circle fa-lg'></i></a>";

            output.push("<li><strong>", escape(f.name), "</strong> - ", removeLink, "</li> ");
        }

        $(this).children(".fileList").append(output.join(""));
    });
};

$(document).on("click",".removeFile", function(e){
    e.preventDefault();
    var fileName = $(this).parent().children("strong").text();
      // loop through the files array and check if the name of that file matches FileName
    // and get the index of the match
    for(i = 0; i < filesToUpload.length; ++ i){
      if(filesToUpload[i].name == fileName){
        
        // remove the one element at the index where we get a match
        filesToUpload.splice(i, 1);
      } 
    }

    // remove the <li> element of the removed file from the page DOM
    $(this).parent().remove();
});

$("#files1").fileUploader(filesToUpload);

a.ak
  • 659
  • 2
  • 12
  • 26
Ken09
  • 11
  • 3
  • Why don't you use a ready-made solution? e.g: [jQuery File Upload](https://blueimp.github.io/jQuery-File-Upload/) **or** [Bootstrap File Input](https://plugins.krajee.com/file-input) – adampweb Apr 12 '21 at 07:42
  • @AdamP. Im sort of new to MVC and codeigniter so i dont dare to try plugin first – Ken09 Apr 12 '21 at 08:01

0 Answers0