0

I have an input to upload an excel file and a hidden input

<input type="file" id="file">

<input type="hidden" id="file_submit">

When I choose file in input type file, I want to set its value to hidden input below and retrieve in AJAX function, then I will reset input file for next upload, prevent ERR_UPLOAD_FILE_CHANGED error.

Here is my code in AJAX:

var formData = new FormData();
formData.append('file', $('#file_submit').val());


$.ajax({
    url: "{{ route('admin.handle-import') }}",
    headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
    method: "POST",
    data: formData,
    enctype: 'multipart/form-data',
    processData: false,
    contentType: false,
    success: function(res) {
         $('file').val(''); //reset input file
    }
});

I tried this code to set value for hidden input:

document.getElementById('file').onchange = function() {
    $('#file_submit').val($(this).prop('files'));
};

And in my controller, I get by code $request->file;. But it only return "[object FileList]". I really don't know what I have to do now.

Can you give me a solution for this?

Thank you very much

Tomato
  • 759
  • 2
  • 14
  • 26
  • I have no idea what a `FileList` is, but I am assuming it is sort of an array-object like element. What happens if you change to `$(this).prop('files')[0]` ? Try to also debug it yourself. Write a `debbuger;` before that line, so JS will stop there and you can manually run `$(this).prop('files')` in the chrome console and see the result, so you can understand more. Also, if you search `FileList` in google you will get the [official documentation](https://developer.mozilla.org/en-US/docs/Web/API/FileList)... There is a super really good example and explanation about how to use it ! – matiaslauriti Aug 02 '21 at 02:58
  • Why not save the values in a variable instead of storing them in a hidden input? – Farshid Rezaei Aug 02 '21 at 05:36
  • I searched for "*file upload ajax "object FileList"*" and turned up several results here which I think answer the question, eg https://stackoverflow.com/questions/42917781/parse-files-in-filelist-object, https://stackoverflow.com/questions/20493216/javascript-pass-input-file-to-php, https://stackoverflow.com/questions/39989967/when-uploading-file-via-ajax-it-always-returns-as-file-info, https://stackoverflow.com/questions/43491311/how-to-get-multiple-image-file-data-in-controller-of-laravel ... – Don't Panic Aug 02 '21 at 06:23
  • Does this answer your question? [Parse files in FileList object](https://stackoverflow.com/questions/42917781/parse-files-in-filelist-object) – Don't Panic Aug 02 '21 at 06:23

0 Answers0