Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove selected file(s) before upload with Javascript

Say I have a form that allows users to upload multiple images, which are appended with an option to remove them if they don't want to upload that particular photo.

Is it possible to remove the value from the files object of the one that they removed (e.g. didn't want to upload)?

like image 822
bob_cobb Avatar asked Feb 18 '12 01:02

bob_cobb


People also ask

How do I unselect a selected file?

Pressing the Ctrl key, you can click, or click-and-drag to deselect any cells or ranges within a selection.

How do I remove one specific selected file from multiple files?

How do I delete a single file from input type file multiple? Just assign $('input:file#upload')[0]. files to an Array and then remove items from that array using splice or method of your choice and then use that Array .

How do I remove a file from the FileList JavaScript?

One way to remove a file from a JavaScript FileList is to use the spread operator to convert the FileList to an array. Then we can call splice to remove the file we want. We add multiple to let select multiple files.


2 Answers

FileList has no API to remove entries:

https://developer.mozilla.org/en/DOM/FileList

However you can reconstruct File uploader using XHR2 and AJAX and filter in content there. This implies doing XHR2 and AJAX upload and is not suitable for traditional <form> uploads.

https://developer.mozilla.org/en/Using_files_from_web_applications

like image 178
Mikko Ohtamaa Avatar answered Oct 04 '22 20:10

Mikko Ohtamaa


If you are using a standard form with a set of standard file inputs then you can do it like this http://jsfiddle.net/thXre/

$(document).ready(function(){
    $('.remove').click(function(){
        $(this).closest('div').slideUp('slow', function(){$(this).remove();});
    });        
});​

and html code:

<div>
 <input type='file' name='files[]'> <img src='x.gif' class='remove'>
</div>
<div>
 <input type='file' name='files[]'> <img src='x.gif' class='remove'>
</div>
<div>
 <input type='file' name='files[]'> <img src='x.gif' class='remove'>
</div>
like image 31
Cheery Avatar answered Oct 04 '22 22:10

Cheery