user3089871 user3089871 - 3 months ago 15
HTML Question

Delete specific file from formData in javascript/jquery

So i made a script where you can preview multiple images before sending them all with an ajax request. All the script will be c/C at the end of the post, but you can also find it here : http://aeronet.be/TESTIMG/

It works great !

Now i would like to delete a choosen image from my formData array when the user click on the image.
For the moment, when you click on an img it still appears on the SERVER side.

In order to do that, my form data looks like that :

form_data {
'name_of_image' : file_data,
'name_of_image' : file_data,
}


I put the name_of_img in my alt attribute of the img preview, and when you click on the image it does that :

var filename = $(this).attr('alt');
var newfilename = filename.replace(/\./gi, "_");
delete form_data[newfilename];
$(this).remove();


I change the "." with "_" because on my server side the array looks like that

array (size=1)
'favicon_ico' =>
array (size=5)
'name' => string 'favicon.ico' (length=11)
'type' => string 'image/x-icon' (length=12)
'tmp_name' => string 'C:\wamp\tmp\php96C9.tmp' (length=23)
'error' => int 0
'size' => int 145388


So my question is : How can i delete a given img from my formData array before sending it ?

HTML :

<input id="avatar" type="file" name="avatar[]" multiple />
<button id="upload" value="Upload" type="button">upload</button>

<div class="preview">
</div>

<div class="return_php"></div>

<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>


javascript/jquery :

$(document).ready(function(){
var form_data = new FormData();
var number = 0;

/* WHEN YOU UPLOAD ONE OR MULTIPLE FILES */
$(document).on('change','#avatar',function(){
console.log($("#avatar").prop("files").length);
len_files = $("#avatar").prop("files").length;
for (var i = 0; i < len_files; i++) {
var file_data = $("#avatar").prop("files")[i];
form_data.append(file_data.name, file_data);
number++;
var construc = '<img width="200px" height="200px" src="' + window.URL.createObjectURL(file_data) + '" alt="' + file_data.name + '" />';
$('.preview').append(construc);
}
});

/* WHEN YOU CLICK ON THE IMG IN ORDER TO DELETE IT */
$(document).on('click','img',function(){

var filename = $(this).attr('alt');
var newfilename = filename.replace(/\./gi, "_");
delete form_data[newfilename];
$(this).remove();

});

/* UPLOAD CLICK */
$(document).on("click", "#upload", function() {
$.ajax({
url: "target.php",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with form_data
type: 'post',
success: function(data){
$('.return_php').html(data);
}
})
})
});


PHP - TARGET.PHP

<?php


var_dump($_FILES);

?>

Answer

Use the delete() method:

form_data.delete($(this).attr('alt'))
$(this).remove()