Dill Gates
Dill Gates

Reputation: 119

Send multiple files to JS object and prepare for Ajax post

Check the code bellow. Here i am trying to insert files to js object then send to backend mvc5 controller to further processing. But problem is that when i when i trigger #btn-HighlightUpdate click jquery throws error in console says: jquery-3.3.1.js:8463 Uncaught TypeError: Illegal invocation. How can i fix it and prepare to send via ajax post? Specially plz check if i am inserting proper value to object on line var file = $(this).find(".hpicFile"); data.push({ Img: file });

Html:

<div class="row" id="hbar">
</div>
<div class="card-footer" style="text-align:right;">
    <button class="btn btn-secondary" id="btn-Newbar">New Bar</button>
    <button class="btn btn-secondary" id="btn-HighlightUpdate">Update Changes</button>
</div>

Dynamic Html:

$("#btn-Newbar").on("click", function () {
    $("#hbar").append("<div class='col-4 wholeBar' style='margin-bottom:20px;'><div class='row'><div class='col-3'><img src='' class='catHpic' style='height:80px;width:80px;'></div><div class='col-9'><input type='file' class='hpicFile'><div class='input-group mb-3' style='margin-top:10px;'><div class='input-group-prepend'><span class='input-group-text url'>URL</span></div><input type='text' class='form-control hurl' aria-describedby='basic-addon1' value=''></div></div></div></div>");
});

Jquery:

$(document).on("click", "#btn-HighlightUpdate", function () {
    var data = [];
    //data.push({ "Img": "fff" });

    $(".wholeBar").each(function (key, value) {
        var file = $(this).find(".hpicFile");
        data.push({ Img: file });
    });

    console.log(data);

    $.post('/Controller/UploadFiles', { Files: data }).done(function (data) {

        console.log(data);

    });
});

Upvotes: 1

Views: 78

Answers (1)

Always Helping
Always Helping

Reputation: 14570

You can use to $.ajax to with type POST to send data to your controller.

I have fixed up your code which needed a formData to store all files (img's) found which we are adding dynamically. We can append those img found to the formData and send that formData your controller for further processing.

There is no need to use an array to push img into it. You can all that on the front end and in the controller just get all files which we are sending and append them to formData.

You were also not sending the correct files but instead your were sending the actual HTML element using .find function. To send the actual object to your controller you need to to use findFiles[0].files[0] and append that to the formData in your $.each function.

I have added some comments for you well on each line of code.

Live Demo:

$("#btn-Newbar").on("click", function() {
  $("#hbar").append("<div class='col-4 wholeBar' style='margin-bottom:20px;'><div class='row'><div class='col-3'><img src='' class='catHpic' style='height:80px;width:80px;'></div><div class='col-9'><input type='file' class='hpicFile'><div class='input-group mb-3' style='margin-top:10px;'><div class='input-group-prepend'><span class='input-group-text url'>URL</span></div><input type='text' class='form-control hurl' aria-describedby='basic-addon1' value=''></div></div></div></div>");
});

//display highlight pic real time 
$(document).on("change", ".hpicFile", function(e) {
  var imgSrc = $(this).parent('div').prev().find('.catHpic') //find img
  if (e.target.files[0] != null) {
    //console.log(e.target.files[0]);
    $.each(this.files, function(key, file) {
      var reader = new FileReader();
      reader.onload = function(e) {
        //display images real time
        imgSrc.attr('src', e.target.result);
      }
      reader.readAsDataURL(file);
    });
  }
});

//Get all the files and send via ajax to your controller
$(document).on("click", "#btn-HighlightUpdate", function() {

  //FormData
  var formData = new FormData()

  $(".wholeBar").each(function(key, value) {
    var findFiles = $(this).find(".hpicFile") //find the element
    var file = findFiles[0].files[0] //get the actual file object
    formData.append('files[]', file) //append all files to formData
  });


  //Ajax request
  $.ajax({
    url: "/Controller/UploadFiles",
    type: "POST",
    processData: false,
    contentType: false,
    data: formData, //Send form Data
    success: function(response) {
      console.log(response)
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log(textStatus, errorThrown);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row" id="hbar">
</div>
<div class="card-footer" style="text-align:right;">
  <button class="btn btn-secondary" id="btn-Newbar">New Bar</button>
  <button class="btn btn-secondary" id="btn-HighlightUpdate">Update Changes</button>
</div>

Upvotes: 1

Related Questions