I want to add Image File in input type file programmatically and with that it is viewed in a div.
all the images has a cross Button. When it is clicked the image is deleted and all other image is set as value of the input type file for submitting a form.
Html:
<div class="row" id="picture_div">
<div class="col-md-4">
<div class="input-group input-group-sm input-group-primary">
<label class="input-group-addon" for="picture"> Attachment</label>
{{Form::file('picture[]', ['class' => 'form-control', 'accept' => '.png, .jpg, .jpeg', 'id' => 'image_input',"onChange"=>"previewImages(this.files)", "multiple" => true ,"placeholder"=> "" ])}}
</div>
</div>
<div class="col-md-8">
@if ($formType=='edit' && $bd_lead != null && !empty($bd_lead->BdLeadGenerationPictures[0]->picture))
<div id="photo_preview">
@foreach ($bd_lead->BdLeadGenerationPictures as $item)
<img src="{{ asset("storage/{$item->picture}") }}" id="picture" width="40px" height="40px" alt="Attachment">
@endforeach
</div>
@else
<div id="photo_preview">
</div>
@endif
</div>
</div>
Javascript:
<script>
let selectedImages = [];
// // Preview all images
function previewImages(files) {
selectedImages = [...files];
let imageList;
let a = document.createElement('DIV')
a.setAttribute('class','d-flex')
let b;
for(let i = 0; i < selectedImages.length; i++) {
b = document.createElement('DIV')
b.setAttribute('class','position-relative')
let file = window.URL.createObjectURL(selectedImages[i]);
b.innerHTML = `
<span onclick="DelItem(${i})" class="dtl" style="">x</span>
<img src="${file}" id="p-${i}" width="40px" height="40px" alt="photo-${i}" class="mr-2">
`;
a.appendChild(b)
}
PHOTO_DIV.empty().append(a);
document.getElementById('image_input').files = selectedImages;
}
function DelItem(idx){
let from = idx;
let to = idx + 1;
let dat = selectedImages.splice(from, to);
previewImages(selectedImages);
}
</script>
The Error I get
create:810 Uncaught TypeError: Failed to set the 'files' property on 'HTMLInputElement': Failed to convert value to 'FileList'.
The Error I get when I use document.getElementById('image_input').value= selectedImages;
create:810 Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string
It is not working.How could i do such task..