0

How can I pass a multiple file value to controller in laravel using ajax?

Here's what I'm trying to do

Blade

<input id="attachment" name="attachment[]" type="file" class="form-control col-md-6" multiple>
<button type="submit" class="btn btn-primary"><i class="fa fa-plus"></i></button>

JS

$(document).on('click', '#addAttachment', function(e)
{
  e.preventDefault();
  e.stopPropagation();
  $.ajax
  ({
    type: 'POST',
    url: '/inventory/attach/'+$('input[name=id]').val(),
    data: {
      '_token' : $('input[name=_token]').val(),
      'attachment' : $('input[name=attachment]').val(),
    },
    success: function(attachment)
    {
      var attach = '<a href="/attachment/asset/'+attachment.attachment+'"><span class="fas fa-download" style="font-size: 18px"></span>'+attachment.attachment+'</a>'
      $('#div_attachment a').remove();
      $('#div_attachment').append(attach);
      swal({
        title: 'Successful!',
        text: 'This will automatically close in 2 seconds',
        icon: 'success',
        timer: 2000,
      });
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      swal({
        title: 'Error!',
        text: 'Please check your connection or contact the administrator!',
        icon: 'error',
      });
    }
  });
});

Its not passing the file values on controller and just giving me a null. I also tried to put [] into this $('input[name=attachment]').val() but its giving me an error.

Any help would be appreciated. Thank you.

Jovs
  • 852
  • 7
  • 23
  • Does this answer your question? [jQuery Ajax File Upload](https://stackoverflow.com/questions/2320069/jquery-ajax-file-upload) – 04FS Nov 11 '19 at 12:17
  • You can not perform a file upload by trying to read the input’s value / .val() in the first place, so go read up on how to handle that properly. – 04FS Nov 11 '19 at 12:18
  • Ohh so its impossible. – Jovs Nov 11 '19 at 12:20
  • No, it’s not impossible. The question I linked to contains explanations of how it can be done. (And if that is not enough, feel free to add your own research.) – 04FS Nov 11 '19 at 12:22

0 Answers0