Having an error in uploading file using js - javascript

When I am Uploading a file using the FileReader library the first time it's uploaded on the first click but the second time it is uploaded when I click on the button second time I am attaching a video link in which you can see the problem and attaching the code as well.
https://drive.google.com/file/d/1OzJLCA7URBcRy_5m_QVWAiLzo8l9eoqd/view
const imgPreviewing = (selected) => {
let img = myImgElement
if (selected.files && selected.files[0]) {
var reader = new FileReader();
reader.onload = function () {
let src = reader.result;
img.setAttribute("src", src);
};
reader.readAsDataURL(selected.files[0]);
}
};
Thank You.

Related

converting from html to png image on initial button click

I am converting part of the html elements into canvas and converting that into png image. It is working fine but the problem is at the first click it is not converting the html to convas and canvas to png.
//HTML To Image on button click
$("#btn-Convert-Html2Image").on('click', function () {
html2canvas(element, {
onrendered: function (canvas) {
getCanvas = canvas;
}
});
setTimeout(function() {
var imgageData = getCanvas.toDataURL("image/png");
var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream");
$("#btn-Convert-Html2Image").attr("download", "your_pic_name.png").attr("href", newData);
},400)
});
Is that anything done wrong. Please see the fiddle link
At first click you are binding png dataURL to #btn-Convert-Html2Image anchor and when 2nd time you click on this link already bound data is downloaded you can use this approach to overcome this issue.
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
}
$("#btn-Convert-Html2Image").on('click', function () {
html2canvas(element, {
onrendered: function (canvas) {
var imgageData = canvas.toDataURL("image/png");
var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream");
downloadURI(newData,"your_pic_name.png");
}
});
});
JSFiddle link
Good news: You make everthing right!
The last line of code says : Set the atribute of the download button to your image. Thast good but to late. You have already clicked the button. So wehn you click the button again the image from the last run will be downloaded and a new one will be generated and linked to the button.
You simply have to force the download AFTER you have generated the image. For example by forcing a URI download ...

How to load a file into a html5 audio tag

How would a I load a audio file from a <input type="file"> tag into a audio tag?
I have tried :
<input type="file" id="file"></input>
<script>
var file = document.getElementById("file");
var audio = document.createElement("audio");
audio.src = file.value;
document.write(audio)
</script>
I believe it will satisfy your needs. First, the file input needs to be bound via JavaScript or jQuery (if you prefer). You can use Blob browser support
The following is a very basic example;
<input type="file" id="file"></input>
<audio id="audio" controls autoplay></audio>
We bind the #file for changes using AddEventListener as below
// Check for BlobURL support
var blob = window.URL || window.webkitURL;
if (!blob) {
console.log('Your browser does not support Blob URLs :(');
return;
}
document.getElementById('file').addEventListener('change', function(event){
consolePrint('change on input#file triggered');
var file = this.files[0],
fileURL = blob.createObjectURL(file);
console.log(file);
console.log('File name: '+file.name);
console.log('File type: '+file.type);
console.log('File BlobURL: '+ fileURL);
document.getElementById('audio').src = fileURL;
});
Or the other hand, here's a nice and more interactive example I created
<iframe style="height:600px;width:102.7%;margin:-10px;overflow:hidden;" src="//jsfiddle.net/adamazad/0oy5moph/embedded/result,js,html,css/" allowfullscreen="allowfullscreen" frameborder="0"></iframe>
var wrap = document.getElementById("wrap");
var file = document.getElementById("file");
var audio = document.createElement("audio");
file.onchange = function() {
audio.src = file.value;
wrap.appendChild(audio);
};
<div id="wrap">
<input type="file" id="file">
</div>
This is to realize the train of thought, but this also cannot achieve, because url that the upload is not local url, You can discuss with me in the comments section
I have developed an es6 code to load a file into an Audio element with a Promise that catches errors and resolves on success
//functions:
function setSrcObject(element, f) {
if ('srcObject' in element) {
try {
// eslint-disable-next-line no-param-reassign
element.srcObject = f; // this is the new way. only safary supports muliplt inputs, it is possible to put here media streams and files and blobs, but current new browsers support only media stream so need a fallback.
} catch (e) {
if (e.name !== 'TypeError') throw e;
// Avoid using this in new browsers, as it is going away.
// eslint-disable-next-line no-param-reassign
element.src = URL.createObjectURL(f);
}
}
// eslint-disable-next-line no-param-reassign
else element.src = URL.createObjectURL(f);
}
function loadAudioFile(audio, file) {
let onloadeddataResolve;
let onloadeddataReject;
// once
function onloadeddataEv() {
onloadeddataResolve();
audio.removeEventListener('loadeddata', onloadeddataEv);
audio.removeEventListener('error', onerrorEv);
}
function onerrorEv(e) {
onloadeddataReject(e.srcElement.error);
audio.removeEventListener('loadeddata', onloadeddataEv);
audio.removeEventListener('error', onerrorEv);
}
audio.addEventListener('loadeddata', onloadeddataEv);
audio.addEventListener('error', onerrorEv);
const promise = new Promise((resolve, reject) => {
onloadeddataResolve = resolve;
onloadeddataReject = reject;
}); // inversion of control promise
// try load it:
try {
// audio.src = url; // = http://example.org/myfile.mp3 or .ogg
setSrcObject(audio, file);
audio.load();
} catch (e) {
audio.removeEventListener('loadeddata', onloadeddataEv);
audio.removeEventListener('error', onerrorEv);
onloadeddataReject(e);
}
return promise;
}
//example:
let audio = new Audio(); // create audio element
audio.autoPlay=false;
filefield.oninput=async function test() {
try {
const f = filefield.files[0]; // take first file
await loadAudioFile(audio, f); // load the file
await audio.play();
} catch(e) { console.log(e.stack?e.stack:e) }
}
playpause.onclick = async () => { if( audio.paused) await audio.play(); else await audio.pause(); };
<input type="file" id="filefield" multiple="multiple" accept="audio/mpeg, audio/mp4, audio/ogg">
<input id="playpause" value="play pause" type="button">
this solution was a part of a playlist player object I have developed
https://jsfiddle.net/shimondoodkin/7zmhsg30/20/
related solution, play audio using web audio API
https://jsfiddle.net/shimondoodkin/251wx8ys/31/

Control load html with: new Image().src = HTML_URL

I am loading in browser cache next page with:
new Image().src = 'HTML_URL';
How do I control end of loading? If loading NOT an image -- always calling onerror.
I can't use jQuery.
Use onerror callback.
var image = new Image();
image.src = 'HTML_URL';
image.onerror = function () {
alert('I failed');
}

Filereader api image onload event for tiff image format not triggering

I am using HTML5 file reader api to show the image preview before uploading the image to server but the problem is when i upload a tiff format image the on load image event is not triggering please see the code below
$('#file').on('change', function (e) {
if (window.FileReader) {
var reader = new FileReader();
reader.readAsDataURL(e.target.files[0]);
reader.onload = function (e) {
var image = new Image;
image.src = e.target.result;
image.onload = function () {
alert();
};
};
} else {
alert('FileReader API is not supported in your browser, please use Firefox, Safari, Chrome or IE10!')
}
});
http://jsbin.com/qajexuwe/1

JS - readAsDataURL blocks browser activity

While I am loading a File into the browser I want to show an animated loading gif to the user. But if the file is very big the browser seems so buisy, that the animation of my gif does not work. What can I do to visualise the loading?
HTML
<img id="loader" src="img/load.gif" />
JS
reader.readAsDataURL(file);
reader.onloadend = function(){
document.getElementById('loader').style.display='none';
var source = reader.result;
document.getElementById('img').setAttribute( 'src', source);
}
document.getElementById('loader').style.display='block';
In theory, what you have should work, as the read operation is asynchronous. Maybe it's the onloadend callback that is blocking the execution. In any case, you could try this:
reader.onloadend = function(){
document.getElementById('loader').style.display='none';
var source = reader.result;
document.getElementById('img').setAttribute( 'src', source);
}
document.getElementById('loader').style.display='block';
// Make sure to start loading only after the loader was displayed
// (give the browser a chance to repaint)
setTimeout(function() {
reader.readAsDataURL(file);
}, 40);
The loaded event should be hooked first. Try this:
reader.onloadend = function(){
document.getElementById('loader').style.display='none';
var source = reader.result;
document.getElementById('img').setAttribute( 'src', source);
}
reader.readAsDataURL(file);
document.getElementById('loader').style.display='block';

Categories