use same function for multiple file upload events - javascript

I have used js-xlsx plugin to parse JSON from an excel file. I am parsing JSON from multiple excel files and I want to use the same parsing function to load the result in multiple dropdowns. I have two upload file inputs and two corresponding dropdowns. I am able to get the xlFileName and sheetNames only for the first dropdown. If I want to upload a different excel file using the second file upload input and want to load the xlFileName and sheetNames for the corresponding excel file in the second dropdown how can I use the same JS functions to achieve this. Thanks in advance. (I have tried switch case to get the ids of upload file inputs but didn't know how to get it done right)
HTML:
<input type="file" style="display:none;" name="files" id="inputFile1" />
<span data-bind="text: fileNameXl1"></span>
<select id="dropdown3" required="required" class="form-control select2" data-bind="options:xlnames,value:selectedSheetname1,
selectedOptions: chosenFile,optionsCaption:'Please Select Sheet Name'">
</select>
<input type="file" style="display:none;" name="files" id="inputFile2" />
<span data-bind="text: fileNameXl1"></span>
<h4 class="header-title m-t-0 m-b-30">Select Sheet name(Macro):</h4>
<select id="dropdown4" required="required" class="form-control select2" data-bind="options:xlnames1,value:selectedSheetname2,
selectedOptions: chosenFile,optionsCaption:'Please Select Sheet Name'">
</select>
JS:
self.selectedSheetname1 = ko.observable("");
self.selectedSheetname2 = ko.observable();
self.selectedSheetname3 = ko.observable();
self.chosenFile = ko.observable();
self.xlnames = ko.observableArray([]);
self.xlnames1 = ko.observableArray([]);
self.fileNameXl1 = ko.observable();
self.handleFile = function(e) {
var files = e.target.files;
var f = files[0];
{
var reader = new FileReader();
xlFileName = f.name;
self.fileNameXl1(xlFileName);
console.log(xlFileName);
reader.onload = function(e) {
if(typeof console !== 'undefined') console.log("onload", new Date());
var data = e.target.result;
var wb;
var arr = fixdata(data);
wb = X.read(btoa(arr), {type: 'base64'});
process_wb(wb);
}
}
reader.readAsArrayBuffer(f);
};
self.fixdata = function(data) {
var o = "", l = 0, w = 10240;
for(; l<data.byteLength/w; ++l) o+=String.fromCharCode.apply(null,new Uint8Array(data.slice(l*w,l*w+w)));
o+=String.fromCharCode.apply(null, new Uint8Array(data.slice(l*w)));
return o;
};
self.process_wb = function(wb) {
var output = "";
output = JSON.stringify(to_json(wb), 2, 2);
var parse = JSON.parse(output);
sheetNames = Object.keys(parse);
console.log("this is output");
console.log(sheetNames);
self.xlnames(sheetNames);
if(typeof console !== 'undefined') console.log("output", new Date());
};
self.to_json = function(workbook) {
var result = {};
workbook.SheetNames.forEach(function(sheetName) {
var roa = X.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
if(roa.length > 0){
result[sheetName] = roa;
}
});
return result;
};
self.loadSheetNamesB25 = function(e){
self.xlnames([]);
self.handleFile(e);
};
self.loadSheetNamesB41 = function(e){
self.xlnames1([]);
self.xlnames2([]);
self.handleFile(e);
};
if(xlf1.addEventListener) xlf1.addEventListener('change', self.loadSheetNamesB25, false);
if(xlf2.addEventListener) xlf2.addEventListener('change', self.loadSheetNamesB41, false);

Related

Javascript save video file to server in javascript

I have <input type="file" name="Video" id="videoSelect" accept="video/mp4" class="FileUpload" /> in my HTML and I want to save the file selected on my server. I already have
var videoID = uuidv4();
var VideoFile = videoSelector.files[0];
var reader = new FileReader();
reader.readAsDataURL(VideoFile);
var senddata = new Object();
senddata.name = videoID;
senddata.size = VideoFile.size;
senddata.type = VideoFile.type;
reader.addEventListener(
"load",
function () {
vidprv.src = reader.result;
vidprv.style.display = "block";
senddata.fileData = reader.result;
},
false
);
in my JavaScript file. I don't know how to save it to the server now

How to access to specific row of excel file using Javascript

I am reading random row of large Excel file using Javascript. But it is taking some time for example when I am working with 300.000 row data in excel file. I need fast way.
<body>
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" onclick="Upload()" />
<!-- <input type="button" id="upload" value="Random" onclick="ProcessExcel()" /> -->
<hr />
<h1 id="exc">Hello</h1>
<p id="her"></p>
<p id="limm"></p>
<div id="dvExcel"></div>
<script type="text/javascript">
// var gl_ex = "";
function Upload() {
//Reference the FileUpload element.
var fileUpload = document.getElementById("fileUpload");
//Validate whether File is valid Excel file.
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.xls|.xlsx)$/;
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
//For Browsers other than IE.
if (reader.readAsBinaryString) {
reader.onload = function (e) {
ProcessExcel(e.target.result);
};
reader.readAsBinaryString(fileUpload.files[0]);
} else {
//For IE Browser.
reader.onload = function (e) {
var data = "";
var bytes = new Uint8Array(e.target.result);
for (var i = 0; i < bytes.byteLength; i++) {
data += String.fromCharCode(bytes[i]);
}
ProcessExcel(data);
// gl_ex = data;
//alert("Uploaded.");
};
reader.readAsArrayBuffer(fileUpload.files[0]);
}
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid Excel file.");
}
};
function ProcessExcel(data) {
//var data = "";
//data = gl_ex;
//Read the Excel File data.
var workbook = XLSX.read(data, {
type: 'binary'
});
//Fetch the name of First Sheet.
var firstSheet = workbook.SheetNames[0];
//Read all rows from First Sheet into an JSON array.
var excelRows = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[firstSheet]);
var len = excelRows.length;
var rand_num = Math.floor((Math.random() * len) + 1);
document.getElementById("her").innerHTML = rand_num;
document.getElementById("limm").innerHTML = len;
document.getElementById("exc").innerHTML = excelRows[rand_num-1].Name;
};
</script>
</body>
As in example shown I am reading random row from Excel file. I think javascript is reading whole excel file sequentially. Can I read specific row data in faster way?

How to display key based values from a text file?

I am working on a text file uplaoding process, where you can display the values based on a key such as First Name. Here is the sample text
First Name : Joe
Last Name : Smith
Age : 21
Now how can I display only the values which is based on the key?
function process() {
var input = fileInput.get(0);
console.log(input);
var reader = new FileReader();
var textFile = input.files[0];
reader.readAsText(textFile);
$(reader).on('load', processFile);
}
function processFile(e) {
var file = e.target.result,
results;
if (file && file.length) {
results = file.split("\n");
var FirstName = results[0];
var LastName = results[1];
var Age = results[3];
alert(FirstName);
alert(LastName);
alert(Age);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="file" id="files" />
<button id="upload" onclick="process()">Upload</button>
</form>
Here is a demo working in base of your code, the matter you got is the DOM selector of the input mine is this
var input = document.getElementsByTagName('INPUT')[0];
nd the all demo is :
function process() {
var input = document.getElementsByTagName('INPUT')[0];
console.log(input);
var reader = new FileReader();
var textFile = input.files[0];
reader.readAsText(textFile);
$(reader).on('load', processFile);
}
function processFile(e) {
console.log(e);
var file = e.target.result,
results;
if (file && file.length) {
results = file.split("\n");
var FirstName = results[0];
var LastName = results[1];
var Age = results[3];
alert(FirstName);
alert(LastName);
alert(Age);
}
}

base64 encoded image not working in the submit button

Here i did multiple file images with base64 conversion , everything working fine , for my requirement user select the multiple images and click the submit button means i have to take the values(file) and converted to base64 encoded string,here when select image that time it will working fine but going submit the button i am getting undefined how to solve this error
$(document).ready(function(){
$("input[name=property_images]").change(function() {
var imgBase64Arr = [];
var files = this.files;
for (var i = 0; i < files.length; i++) {
(function(i){
var FR = new FileReader();
FR.onload = function(e) {
var res = e.target.result ;
var arr1 = res.split(",");
var property_image = arr1[1] ;
imgBase64Arr.push( property_image);//adding base64 value to array
if(i === files.length -1)//after all files are porcessed
myFunction(imgBase64Arr)
};
FR.readAsDataURL(files[i]);
})(i);
}
});
});
function myFunction(imgBase64Arr){
console.log(imgBase64Arr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="file" name="property_images" multiple="multiple" />
<input type="button" value="submit" onclick="myFunction()">
When press submit button you call "myFunction" without passing anything..
$(document).ready(function(){
var imgBase64Arr = [];
$("input[name=uploadBtn]").click(function(){
console.log(imgBase64Arr);
});
$("input[name=property_images]").change(function() {
imgBase64Arr = [];
var files = this.files;
for (var i = 0; i < files.length; i++) {
(function(i){
var FR = new FileReader();
FR.onload = function(e) {
var res = e.target.result ;
var arr1 = res.split(",");
var property_image = arr1[1] ;
imgBase64Arr.push( property_image);//adding base64 value to array
if(i === files.length -1)//after all files are porcessed
myFunction(imgBase64Arr)
};
FR.readAsDataURL(files[i]);
})(i);
}
});
});
function myFunction(imgBase64Arr){
console.log(imgBase64Arr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="file" name="property_images" multiple="multiple" />
<input type="button" name="uploadBtn" value="submit">
Your imgBase64Arr variable is not globally defined. Please defined it globally.

While JavaScript File Reader With Pushing Data to Global Array

I have posted code below and trying to upload text files:
Problem is to store data in JavaScript array, ifileData always returns blank/null values.
<input type="file" name="ic-files[]" class="ic-input" multiple="true" />
<input type="file" name="ic-files[]" class="ic-input" multiple="true" />
<input type="file" name="ic-files[]" class="ic-input" multiple="true" />
<input type="file" name="ic-files[]" class="ic-input" multiple="true" />
<script>
var ifileData = new Array();
$(document).on('click','#start', function()
{
$('.ic-input').each(function()
{
if($(this).val() != "")
{
var inCorrectFile = $(this).get(0).files;
for (var i = 0; i < inCorrectFile.length; i++)
{
var reader = new FileReader();
reader.onload = function(e)
{
/* Temp Object */
var ipfileData = {};
var fileContent = this.result;
ipfileData['data'] = fileContent;
ifileData.push(ipfileData);
}
reader.readAsText(inCorrectFile[i], "UTF-8");
}
}
});
alert(JSON.stringify(ifileData));
});
</script>
also i've posted code to https://jsfiddle.net/3aexs7wp/3/
Try substituting change event for click event ; adjusting delegated selector to .ic-input
var ifileData = new Array();
$(document).on('change', '.ic-input', function() {
$('.ic-input').each(function() {
if ($(this).val() != "") {
var inCorrectFile = $(this).get(0).files;
for (var i = 0; i < inCorrectFile.length; i++) {
var reader = new FileReader();
reader.onload = function(e) {
/* Temp Object */
var ipfileData = {};
var fileContent = this.result;
ipfileData['data'] = fileContent;
ifileData.push(ipfileData);
console.log(ifileData)
}
reader.readAsText(inCorrectFile[i], "UTF-8");
}
}
});
// alert(JSON.stringify(ifileData));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="file" name="ic-files[]" class="ic-input" multiple="true" />
jsfiddle https://jsfiddle.net/3aexs7wp/4/

Categories