Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript delete File from FileList to be uploaded

There is the code https://jsfiddle.net/bfzmm1hc/1 Everything looks fine but I want to delete some of the files from the set.

I have already found these:

  • How to remove one specific selected file from input file control
  • input type=file multiple, delete items

I know that FileList object is readonly, so I can just copy the files to a new array. But what should I do with this new array of File objects? I can't assign it to the files property...

like image 749
user1128677 Avatar asked Apr 19 '26 11:04

user1128677


1 Answers

I found a workaround. This will not require AJAX for the request at all and the form can be sent to the server. Basically you could create an hidden or text input and set it's value attribute to the base64 string created after processing the file selected.

<input type=hidden value=${base64string} />

You will probably consider the idea to create multiple input file instead of input text or hidden. This will not work as we can't assign a value to it.

This method will include the input file in the data sent to the database and to ignore the input file you could:

  • in the back-end don't consider the field;
  • you can set the disabled attribute to the input file before serialising the form;
  • remove the DOM element before sending data.

When you want to delete a file just get the index of the element and remove the input element (text or hidden) from the DOM.

Requirements:

  • You need to write the logic to convert files in base64 and store all files inside an array whenever the input file trigger the change event.

Pros:

  • This will basically give you a lot of control and you can filter, comparing files, check for file size, MIME type, and so on..
like image 157
Michael Mammoliti Avatar answered Apr 21 '26 02:04

Michael Mammoliti