fileReader.onload does not run second time, even after selecting different file - javascript

document.getElementById("uploadExcel").addEventListener("click", function () {
$("#uploadExcel").attr('disabled', true);
$('#loader').show();
if (selectedFile) {
var fileReader = new FileReader();
alert("2");
fileReader.onload = function (event) {
alert(event);
var data = event.target.result;
alert("3");
var workbook = XLSX.read(data, {
type: "binary", cellDates: true, dateNF: 'mm/dd/yyyy;#'
});
alert("4");
workbook.SheetNames.forEach(sheet => {
alert("5");
let rowObject = XLSX.utils.sheet_to_row_object_array(
workbook.Sheets[sheet]
);
let jsonObject = JSON.stringify(rowObject);
alert("Get Data");
getData(jsonObject);
//document.getElementById("jsonData").innerHTML = jsonObject;
});
};
alert("6");
fileReader.readAsBinaryString(selectedFile);
} else {
alert("error");
}
});
Now let me explain what is happening:
The page loads and I select the file to upload, it goes through even if it has excel errors, it will take the file and read it, convert it and throw errors.
So then I change that excel file to be error-free and try to click the upload button again, but this time the code enters the above function, and it won't go past fileReader.onload = function (event) it alerts "2" and then stops working.
Can you please tell me why is this happening and how to avoid this without a page reload, because if I do a page reload everything works as expected.
Thanks

Related

jQuery Drag-and-Drop + click Image Upload

I would like to have a simple drop zone to upload image via AJAX and jQuery. I have found some plugins but they are way too customized for what's needed, and I cannot get any of them working properly.
I also would like the drop zone to be clickable, in order to manually choose a file from the OS file dialog.
I found this script, that works fine but where the drop zone is not clickable:
// ---------------------------- drop zone to upload image : '#dropfile'
$(document).on('dragenter', '#dropfile', function() {
return false;
});
$(document).on('dragover', '#dropfile', function(e){
e.preventDefault();
e.stopPropagation();
return false;
});
$(document).on('dragleave', '#dropfile', function(e) {
e.preventDefault();
e.stopPropagation();
return false;
});
$(document).on('drop', '#dropfile', function(e) {
if(e.originalEvent.dataTransfer){
if(e.originalEvent.dataTransfer.files.length) {
// Stop the propagation of the event
e.preventDefault();
e.stopPropagation();
// Main function to upload
upload(e.originalEvent.dataTransfer.files);
}
}
return false;
});
function upload(files) {
var f = files[0] ;
// Only process image files.
if (!f.type.match('image/jpeg')) {
alert(‘The file must be a jpeg image’) ;
return false ;
}
var reader = new FileReader();
// When the image is loaded, run handleReaderLoad function
reader.onload = handleReaderLoad;
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
function handleReaderLoad(evt) {
var pic = {};
pic.file = evt.target.result.split(',')[1];
var str = jQuery.param(pic);
$.ajax({
type: 'POST',
url: ‘url_to_php_script.php’,
data: str,
success: function(data) {
//do_something(data) ;
}
});
}
So I added an invisible file type input, but image data seems to be sent twice. I suppose it's due a bad event propagation with the original drop zone:
// ---------------------------- clickable drop zone with invisible file input '#inputFile'
$('#dropfile).on('click', function() {
$('input#inputFile').trigger('click');
$('input#inputFile').change(function(e) {
upload($('input#inputFile')[0].files);
});
});
I tried to add these lines but data is always sent twice:
$('#dropfile).on('click', function() {
$('input#inputFile').trigger('click');
$('input#inputFile').change(function(e) {
upload($('input#inputFile')[0].files);
// -------------- stop sending data twice ???
e.preventDefault();
e.stopPropagation();
return false;
});
});
I still don't know why data is sent twice but I found a better script here:
https://makitweb.com/drag-and-drop-file-upload-with-jquery-and-ajax/

Javascript inline script onchange not working

i'm having a problem on making my code to adjust to my web server, because of the security purposes, all inline javascript code to my html is not allowed.
everything is already okay i'm just having a hard time converting my other code to pure javascript
Here is my existing code,,,
<label class=qrcode-text-btn><input type=file accept="image/*" capture=environment id="openQRCamera" tabindex=-1></label>
the original code is this
<label class=qrcode-text-btn><input type=file accept="image/*" capture=environment onchange="openQRCamera(this);" tabindex=-1></label>
the onchange is not working because it is inline in the html.
this function needs to open a camera and detect if there is a qr that exists.
here is what i have now on converting it.
document.querySelector("#openQRCamera").addEventListener('onchange', (node) => {
var reader = new FileReader();
reader.onload = function() {
node.value = "";
qrcode.callback = function(res) {
if(res instanceof Error) {
alert("There is no QR detected");
} else {
node.parentNode.previousElementSibling.value = res;
}
};
qrcode.decode(reader.result);
};
reader.readAsDataURL(node.files[0]);
});
here is the original code
function openQRCamera(node) {
var reader = new FileReader();
reader.onload = function() {
node.value = "";
qrcode.callback = function(res) {
if(res instanceof Error) {
alert("There is no QR detected");
} else {
node.parentNode.previousElementSibling.value = res;
}
};
qrcode.decode(reader.result);
};
reader.readAsDataURL(node.files[0]);
}
i am using this website as my source of code, everything is working fine in my localhost, but the server is just strict, and i think that's normal for all the websites.
https://www.sitepoint.com/create-qr-code-reader-mobile-website/
i just been stuck and try to do other solution like adding event listener, and append of input just by using jquery, but it's not working. thanks in advance.
The event listener you are using is faulty, instead of listenning to 'onchange' you have to listen to 'change' like so:
document.querySelector("#openQRCamera").addEventListener('change', () => {
//remove the node as parameter and get it with javascript:
var node = document.getElementById('openQRCamera');
..

NWJS updating progress bar during long loop javascript

I'm having some troubles with javascript.
I'm trying to do a desktop app with NW.JS. I have a .xml file which I drag and drop in my app then it run a function to read the XML do some stuff and save a new file in .csv
It's work fine but now i would be able to update a progress bar during the function...
I tried setInterval and setTimeOut() but I'mhaving always the same result : nothing append until the function is finished.
here is my code
//Same as $(document).ready();
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
//When the page has loaded, run this code
ready(function(){
// prevent default behavior from changing page on dropped file
window.ondragover = function(e) { e.preventDefault(); return false };
// NOTE: ondrop events WILL NOT WORK if you do not "preventDefault" in the ondragover event!!
window.ondrop = function(e) { e.preventDefault(); return false };
var holder = document.getElementById('holder');
holder.ondragover = function () { this.className = 'hover'; return false; };
holder.ondragleave = function () { this.className = ''; return false; };
holder.ondrop = function (e) {
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function (event) {
########I'm doing stuff here to convert file and i want to update the progressbar##########
};
reader.readAsText(file);
//reader.readAsDataURL(file);
return false;
};
});
Thanks for your help
best regards,
After trying the same code in NWJS and Electron, I found the problem to be that any long-running process in the 'main' Chromium process blocks rendering. The solution is to spawn a child process that communicates via Node's IPC. More details in this answer.

Feed FileReader from server side files

I´m starting to customize/improve an old audio editor project. I can import audio tracks to my canvas VIA drag&drop from my computer. The thing is that I also would like to use audio tracks already stored in the server just clicking over a list of available tracks... instead of use the <input type="file"> tags. How can I read the server side files with a FileReader?Ajax perhaps? Thanks in advance.
This is the code for the file reader:
Player.prototype.loadFile = function(file, el) {
//console.log(file);
var reader = new FileReader,
fileTypes = ['audio/mpeg', 'audio/mp3', 'audio/wave', 'audio/wav'],
that = this;
if (fileTypes.indexOf(file.type) < 0) {
throw('Unsupported file format!');
}
reader.onloadend = function(e) {
if (e.target.readyState == FileReader.DONE) { // DONE == 2
$('.progress').children().width('100%');
var onsuccess = function(audioBuffer) {
$(el).trigger('Audiee:fileLoaded', [audioBuffer, file]);
},
onerror = function() {
// on error - show alert modal
var tpl = (_.template(AlertT))({
message: 'Error while loading the file ' + file.name + '.'
}),
$tpl = $(tpl);
$tpl.on('hide', function() { $tpl.remove() })
.modal(); // show the modal window
// hide the new track modal
$('#newTrackModal').modal('hide');
};
that.context.decodeAudioData(e.target.result, onsuccess, onerror);
}
};
// NOTE: Maybe move to different module...
reader.onprogress = function(e) {
if (e.lengthComputable) {
$progress = $('.progress', '#newTrackModal');
if ($progress.hasClass('hide'))
$progress.fadeIn('fast');
// show loading progress
var loaded = Math.floor(e.loaded / e.total * 100);
$progress.children().width(loaded + '%');
}
};
reader.readAsArrayBuffer(file);
};
return Player;
Thanks for the suggestion micronn, I managed to make a bypass without touch the original code. The code as follows is the following:
jQuery('.file_in_server').click(function()
{
var url=jQuery(this).attr('src');//Get the server path with the mp3/wav file
var filename = url.replace(/^.*[\\\/]/, '');
var path="http://localhost/test/audio/tracks/"+filename;
var file = new File([""], filename); //I need this hack because the original function recives a buffer as well as the file sent from the web form, so I need it to send at least the filename
var get_track = new XMLHttpRequest();
get_track.open('GET',path,true);
get_track.responseType="arraybuffer";
get_track.onload = function(e)
{
if (this.status == 200) //When OK
{
Audiee.Player.context.decodeAudioData(this.response,function(buffer){ //Process the audio toward a buffer
jQuery('#menu-view ul.nav').trigger('Audiee:fileLoaded', [buffer, file]); //Send the buffer & file hack to the loading function
},function(){
alert("Error opening file");
jQuery('#newTrackModal').modal('hide');
});
}
};
get_track.send();
});
After this, in the fileLoaded function, the track is added to the editor.
var name = 'Pista ' + Audiee.Collections.Tracks.getIndexCount();
track = new TrackM({buffer: audioBuffer, file: file, name: name}); //being audioBuffer my buffer, file the fake file and name the fake file name
Audiee.Collections.Tracks.add(track);
And... thats it!

How to process an image in url to upload on the server in cordova

I am having a problem with this code. i wanna process the cordova android image url ( ie. stored in localStorage ) to upload in my web server.
function processImages(list, i){
var images = list[i].images;
images && images.forEach(function(image, j){
window.resolveLocalFileSystemURI(image, function(entry) {
var reader = new FileReader();
reader.onloadend = function(evt) {
list[i].images[j] = evt.target.result;
}
reader.onerror = function(evt) {
alert("error");
}
entry.file(function(f) {
//alert("Image is added");
reader.readAsDataURL(f);
}, function(e) {
alert('Image process error : '+e);
});
});
});
}
This code runs good if i am enabling #alert("Image is added"); this alert.
without this alert the app is shutting down by giving error unfortunately appname has stopped.
Its also not working for n number of images of size more than 2mb.
Note : consider async call and image size is more than 2mb each minimum 10 image per record.
Please help me !!!
Thanks

Categories