Deleting image from list - javascript

Here is my text field
<input type="file" name="noteMedia[]" multiple id="ssi-upload" />
Variables
const dT = new DataTransfer();
const fileInput = document.getElementById("ssi-upload");
I'm adding copy and paste feature, so i do this
document.onpaste = function(event){
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
const dTLocal = new DataTransfer();
for (index in items) {
var item = items[index];
if (item.kind === 'file') {
var blob = item.getAsFile();
var reader = new FileReader();
dTLocal.items.add(blob);
fileInput.files = dTLocal.files;
reader.readAsDataURL(blob);
}
}
$("#ssi-upload").change();
i=i+1
}
and here is my #ssi-upload.change()
$("#ssi-upload").change(function(){
$("#imagePreview").html("");
var file = $(this)[0].files[0];
dT.items.add(file);
fileInput.files = dT.files;
imageIndex = 0;
Array.from(dT.items).forEach(item => {
var blob = item.getAsFile();
var image = new Image()
var reader = new FileReader();
var uri = URL.createObjectURL(blob);
var img = new Image();
img.src = uri;
var imagePreview = "<img width = '150px' height='100px' src='"+uri+"'>";
$("#imagePreview").append('<td style="text-align:center; vertical-align:middle">'+imagePreview+'<p class="text-center" align="text-center"> <a onclick="return deleteImage('+imageIndex+');" href="#"> Delete </a></p> </td>');
imageIndex = imageIndex + 1
});
});
So i want to have two ways to adding file, copy paste and default way from the input field. So, the problem is when i'm trying to delete the item deleteImage
function deleteImage(index){
const fileListArr = Array.from(fileInput.files)
fileListArr.splice(index, 1)
$("#ssi-upload").change()
}
The result is instead of remove file it is adding another file. So, how can i fix it ?
JSFiddle

Remove $("#ssi-upload").change() and add class to td like img-preview and pass this params to deleteImage so you can access that element. check the snippet below.
const dT = new DataTransfer();
const fileInput = document.getElementById("ssi-upload");
var i = 0;
let imageIndex = 0;
document.onpaste = function(event){
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
const dTLocal = new DataTransfer();
for (index in items) {
var item = items[index];
if (item.kind === 'file') {
var blob = item.getAsFile();
var reader = new FileReader();
dTLocal.items.add(blob);
fileInput.files = dTLocal.files;
reader.readAsDataURL(blob);
}
}
$("#ssi-upload").change();
i=i+1
}
$("#ssi-upload").change(function(){
$("#imagePreview").html("");
var file = $(this)[0].files[0];
dT.items.add(file);
fileInput.files = dT.files;
imageIndex = 0;
Array.from(dT.items).forEach(item => {
var blob = item.getAsFile();
var image = new Image()
var reader = new FileReader();
var uri = URL.createObjectURL(blob);
var img = new Image();
img.src = uri;
var imagePreview = "<img width = '150px' height='100px' src='"+uri+"'>";
$("#imagePreview").append('<td class="img-preview" style="text-align:center; vertical-align:middle">'+imagePreview+'<p class="text-center" align="text-center"> <a onclick="return deleteImage('+imageIndex+',this);" href="#"> Delete </a></p> </td>');
imageIndex = imageIndex + 1
});
});
function deleteImage(index,obj){
const fileListArr = Array.from(fileInput.files)
fileListArr.splice(index, 1);
console.log(fileListArr);
$(obj).closest('.img-preview').remove();
//$("#ssi-upload").change()
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="noteMedia[]" multiple id="ssi-upload" />
<table class="table" id="imagePreview"><tbody></tbody></table>

Related

Multiple videos upload repeatedly - JavaScript / jQuery

I created a upload for multiples videos, and I'm showing in a thumbnail.
It's working ok until here, the problem is, I select for example 3 videos differently, but when loading my preview for all videos are the same.
HTML:
<div id="thumbnail"></div>
<input type="file" id="upload-file" accept="video/*" multiple/>
JavaScript:
$('div').on('click', '.closeDiv', function () {
$(this).prev().remove();
$(this).remove();
$('#upload-file').val("");
});
var fileDiv = document.getElementById("upload");
var fileInput = document.getElementById("upload-file");
fileInput.addEventListener("change", function (e) {
var filesVAR = this.files;
showThumbnail(filesVAR);
}, false);
function showThumbnail(files) {
debugger
for (var i = 0; i < files.length; i++) {
var file = files[i];
var thumbnail = document.getElementById("thumbnail");
var pDiv = document.createElement("div");
var video = document.createElement("video");
var div = document.createElement("div");
pDiv.setAttribute('class', 'pDiv');
thumbnail.appendChild(pDiv);
video.setAttribute('class', 'imgKLIK5');
pDiv.appendChild(video)
div.innerHTML = "Excluir";
div.setAttribute('class', 'closeDiv');
pDiv.appendChild(div)
video.file = file;
var reader = new FileReader()
reader.onload = (function (aImg) {
return function (e) {
var blobURL = URL.createObjectURL(file);
aImg.src = blobURL;
aImg.setAttribute("controls", "")
};
}(video))
var ret = reader.readAsDataURL(file);
var canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
video.onload = function () {
ctx.drawImage(video, 100, 100);
}
}
}
Check the image results (I selected 3 videos):
But the results:
just need to change the vars to lets and it works fine
$('div').on('click', '.closeDiv', function() {
$(this).prev().remove();
$(this).remove();
$('#upload-file').val("");
});
let fileDiv = document.getElementById("upload");
let fileInput = document.getElementById("upload-file");
fileInput.addEventListener("change", function(e) {
let filesVAR = this.files;
showThumbnail(filesVAR);
}, false);
function showThumbnail(files) {
debugger
for (let i = 0; i < files.length; i++) {
let file = files[i];
let thumbnail = document.getElementById("thumbnail");
let pDiv = document.createElement("div");
let video = document.createElement("video");
let div = document.createElement("div");
pDiv.setAttribute('class', 'pDiv');
thumbnail.appendChild(pDiv);
video.setAttribute('class', 'imgKLIK5');
pDiv.appendChild(video)
div.innerHTML = "Excluir";
div.setAttribute('class', 'closeDiv');
pDiv.appendChild(div)
video.file = file;
let reader = new FileReader()
reader.onload = (function(aImg) {
return function(e) {
let blobURL = URL.createObjectURL(file);
aImg.src = blobURL;
aImg.setAttribute("controls", "")
};
}(video))
let ret = reader.readAsDataURL(file);
let canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
video.onload = function() {
ctx.drawImage(video, 100, 100);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="thumbnail"></div>
<input type="file" id="upload-file" accept="video/*" multiple/>
I hope this helps

How to play audio loaded via file input

I want to load an audio file via input file reader and then be able to play it ...
Here is the process of creating file blob and assign the audio source to this blob:
fileInput.on('change', readFile);
function readFile(e) {
const input = e.target;
if(input.files && input.files[0]) {
const reader = new FileReader();
reader.onload = (e) => {
const binaryData = e.target.result;
const binary = convertDataURIToBinary(binaryData);
const blob = new Blob(binary, {type: input.files[0].type });
console.log('inserting blobXX', blob);
recordedAudioComponent.src = URL.createObjectURL(blob);
data.instructAudios[component] = blob;
console.log('recordedAudioComponent.src', recordedAudioComponent.src);
}
reader.readAsDataURL(input.files[0]);
}
}
And here is the result of above code on console:
Now I'm trying to play the recordedAudioComponent which is an audio tag with the source right?
const recordedAudioComponent = document.getElementById(`recordedAudio-instruct-${component}`);
console.log(recordedAudioComponent)
recordedAudioComponent.play();
And here is the error it produces:
How can I fix this and play the audio?
EDIT: Here is the function to get the blob in the first code:
var BASE64_MARKER = ';base64,';
function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
You don't need any of convertion, blob is actually pretty similar from the file itself and the method URL.createObjectURL accepts file as argument, all you need to do to play the audio file from your browser is set the src attribute as the url created, something like this:
<body>
<input style="display: block;" type="file" onchange="loadAudioFile(this)">
<audio src=" " id="track" controls>
</audio>
<script>
function loadAudioFile(e) {
const url = URL.createObjectURL(e.files[0]);
document.getElementById('track').setAttribute('src', url);
}
</script>
</body>
<input type="file" name="fileInput" id="fileInput">
<script>
const fileInput = document.querySelector('#fileInput');
fileInput.onchange = readFile;
/** #type {AudioNode} */
const audio = document.createElement( 'audio' );
function readFile(e) {
const input = e.target;
if(input.files && input.files[0]) {
const reader = new FileReader();
reader.onloadend = function (e){
audio.src = e.target.result;
audio.play();
}
reader.readAsDataURL(input.files[0]);
}
}
</body>

How to use the loop in the file input change event

Hello I have the following code
function fileValidation() {
var fileInput = document.getElementById('filech');
var filePath = fileInput.value;
var allowedExtensions = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
if (!allowedExtensions.exec(filePath)) {
alert('error .jpeg/.jpg/.png/.gif ');
fileInput.value = '';
return false;
} else {
//Image preview
if (fileInput.files && fileInput.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('imagePreview').innerHTML = '<img src="' + e.target.result + '"/>';
};
reader.readAsDataURL(fileInput.files[0]);
}
}
}
<input id="filech" type="file" name="file_img[]" multiple onchange="return fileValidation()" />
<div id="imagePreview"></div>
To upload photos by
<input id="filech" type="file" name="file_img[]" multiple onchange="return fileValidation()" />
then show
<div id="imagePreview"></div>
I want to show all the pictures and not one
How to use the loop here and thank all
Well as you said you will need a loop, the easiest way would be to use a for loop, like this:
for (var i = 0; i < fileInput.files.length; i++) {
if (fileInput.files && fileInput.files[i]) {
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('imagePreview').innerHTML += '<img src="' + e.target.result + '"/>';
};
reader.readAsDataURL(fileInput.files[i]);
}
}
Note:
Note that I changed it to document.getElementById('imagePreview').innerHTML +=, so it keep printing all the iterated images, otherwise it will just override the preview with the last image content.
But the best practice is to create an img element on each iteration and append it to the preview div:
for (var i = 0; i < fileInput.files.length; i++) {
if (fileInput.files && fileInput.files[i]) {
var reader = new FileReader();
reader.onload = function(e) {
var img = document.createElement("img");
img.src = e.target.result;
document.getElementById('imagePreview').appendChild(img);
};
reader.readAsDataURL(fileInput.files[i]);
}
}
Demo:
function fileValidation() {
var fileInput = document.getElementById('filech');
var filePath = fileInput.value;
var allowedExtensions = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
if (!allowedExtensions.exec(filePath)) {
alert('error .jpeg/.jpg/.png/.gif ');
fileInput.value = '';
return false;
} else {
//Image preview
for (var i = 0; i < fileInput.files.length; i++) {
if (fileInput.files && fileInput.files[i]) {
var reader = new FileReader();
reader.onload = function(e) {
var img = document.createElement("img");
img.src = e.target.result;
document.getElementById('imagePreview').appendChild(img);
};
reader.readAsDataURL(fileInput.files[i]);
}
}
}
}
<input id="filech" type="file" name="file_img[]" multiple onchange="return fileValidation()" />
<div id="imagePreview"></div>

How to save a text to file and read it again but save as binary in javascript

I'm building a file saver from a string using FileSaver.js from a SO question
let byteChars = atob("my string");
let byteNumbers = new Array(byteChars.length);
for (var i = 0; i < byteChars.length; i++) {
byteNumbers[i] = byteChars.charCodeAt(i);
}
let byteArray = new Uint8Array(byteNumbers);
var data:Blob = new Blob([byteArray], {type: "application/octet-stream"});
var filename:string = filename + '.myext';
saveAs(data, filename, true);
Then I have to read it back to "my string" using Javascript's FileReader:
let fr = new FileReader();
fr.onload = (e:FileReaderEvent) => {
let result:any = e.target.result;
//I don't know what I have to do with this type of data to get "my string" back
};
fr.readAsBinaryString(file);
Edit, Updated
write file
let byteChars = atob("my string");
let byteNumbers = new Array(byteChars.length);
for (var i = 0; i < byteChars.length; i++) {
byteNumbers[i] = byteChars.charCodeAt(i);
}
let byteArray = new Uint8Array(byteNumbers);
var data = new Blob([byteArray], {type: "application/octet-stream"});
saveAs(data, "myfile.abc");
read file
<input type="file">
<script>
var reader = new FileReader();
reader.addEventListener("load", function(e) {
document.body.innerHTML += "<br>" + btoa(e.target.result);
});
document.querySelector("input[type=file]")
.addEventListener("change", function(e) {
reader.readAsBinaryString(e.target.files[0])
})
</script>
plnkr http://plnkr.co/edit/0KVhXnd0JpysplDLcAlC?p=preview
You can use TextEncoder(), TextDecoder() or FileReader(), .readAsBinaryString()
var str = "my string";
var encoder = new TextEncoder();
var encodedBytes = encoder.encode(str);
// do file save stuff
var decoder = new TextDecoder();
var decodedBytes = decoder.decode(encodedBytes);
console.log(encodedBytes, decodedBytes);
// alternatively, using `FileReader()`
var reader = new FileReader();
reader.onload = function() {
console.log("FileReader result:", reader.result)
}
reader.readAsBinaryString(new Blob([encodedBytes]))

Send default image with ajax

Hi guys how can i convert a image to object in this code for example:
var img = $('<img id="dynamic">');
img.attr('src', 'http://macreationdentreprise.fr/wp-content/uploads/2012/06/ouvrir-un-restaurant.jpeg');
var obj=img.ConvertToObject();
// so i can now use obj.filename; and obj.data;
The reason to do that is if i wan't to upload this image automatically if the input file isn't set:
<input id="picture_zone_upload_input_ID" type="file" name="picture_zone_upload_input" class="picture_zone_upload_input" multiple title="Choose a file to upload"/>
EDIT
function configure_zone_upload() {
$("#picture_zone_upload_input_ID").change(function (event) {
$.each(event.target.files, function (index, file) {
var reader = new FileReader();
reader.onload = function (event) {
object = {};
object.filename = file.name;
object.data = event.target.result;
//alert("index: " + index);
upload_img_count++;
configure_upload_img(object.data, upload_img_count);
files.push(object);
};
reader.readAsDataURL(file);
});
var files = event.target.files;
for (var x = 0; x < files.length; x++) {
data.append(x, files[x]);
}
//alert(files.length);
AJAX_upload_Profile(data, upload_img_count);
});
}
If there isn't a input file how can i set the my default image to send it with ajax ??
EDIT2
If event.target.files; is null how can i set file from new image:
var files = event.target.files;
for (var x = 0; x < files.length; x++) {
data.append(x, files[x]);
}
//alert(files.length);
AJAX_upload_Profile(data, upload_img_count);
I guess you can do this:
object.filename = file.name || defaultImg;
where defaultImg is a variable which contains a default img with src.
somthing like:
reader.onload = function (event) {
object = {};
object.defaultImg = $('<img>',{"src" : "defaultImg/path/img.jpeg"}); // <--declare here
object.filename = file.name
object.data = event.target.result || object.defaultImg; //<---use it here;
//alert("index: " + index);
upload_img_count++;
configure_upload_img(object.data, upload_img_count);
files.push(object);
};

Categories