JS $.get method file with path - javascript

I want to load a *.csv file from a path which the user can choose.
The path I get: C:\\Users\\...
But the $.get method can't read this path. What does the path have to look like?
$.get(pathAndFile, function (data) {...

If you wanted to read CSV data in JavaScript from a computer you would need to instruct the user to select the file (there is no way around this, with the possible exception of a virus). However once a user selected a file you can read and parse CSV data with a small amount of JavaScript like this (demo)
With this HTML:
<input type="file" id="file" name="file" />
<table id="rows"></table>
And this JavaScript:
var output = $('#rows');
$('#file').on('change', function(evt) {
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++) {
// Only process text files.
if (!f.type.match('text/.*')) {
alert('Unsupported filetype:'+f.type);
continue;
}
var reader = new FileReader();
reader.onloadend = function(evt) {
var rows, row, cols, col, html;
if (evt.target.readyState == FileReader.DONE) {
output.empty();
rows = evt.target.result.match(/[^\r\n]+/g);
for(row = 0; row < rows.length; row++) {
cols = rows[row].split(',');
html = '<tr>';
for(col = 0; col < cols.length; col++) {
html += '<td>'+cols[col]+'</td>';
}
html += '</tr>';
output.append(html);
}
}
};
// Read in the text file
reader.readAsBinaryString(f);
}
});
You can generate an HTML table from the contents of a CSV file (this is based on this excellent site)

function getFile(fileToRead) {
var reader = new FileReader();
reader.readAsText(fileToRead);
// Handle errors load
reader.onload = loadHandler;
reader.onerror = errorHandler;
}
function loadHandler(event) {
var csv = event.target.result;
createChart(csv);
}

Related

Importing data to localstorage

Could anybody help me out sorting the following code or help me in the right direction?
It needs to import data from a .txt file and store it into localstorage as key & value.
Key is before ':' and value comes after it. A new key / value is separated after each ','.
Sample data from .txt file is:
nl-step1chapter1Question6:U2FsdGVkX19bRT84xShxK+29ypgj1d6ZHt+2DVBCUtY=,nl-step1chapter1Question1:U2FsdGVkX1+/Sv61L69bLvQGTkf1A9Uy4jgJ3KZTkzI=,nl-step1chapter1Question4:U2FsdGVkX1+9SVVOvTKeZuaQGj58L5WnEgL8htS0c7U=,jft:320982da-f32a-46a2-a97c-605ebe305518,nl-step1chapter1Question5:U2FsdGVkX19pi8A+PQZ7rBNCWrFeCwl2HdXpV+wWkFk=,nl-step1chapter1Question2:U2FsdGVkX19hnRnpmP3omzYNU0jXd3NtsHM+mvGYBnc=,nl-step1chapter1Question3:U2FsdGVkX1+hPbMRN+x19y7pF73eXoxG0qK1igZYZbA=
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="application/x-javascript">
$(function importData() {
document.getElementById('file').onchange = function () {
//debugger;
var file = this.files[0];
var reader = new FileReader();
reader.onload = function (progressEvent) {
//console.log(this.result.split(','));
var lines = this.result.split(',');
var list = [];
for (var line = 0; line < lines.length; line++) {
list.push(lines[line]);
localStorage.setItem([line],lines);
}
};
reader.readAsText(file);
};
});
</script>
Any help is much appreciated!
The way you are using FileReader doesn't seem correct to me. This is how your importData() function should be:
$(function importData() {
document.getElementById('file').onchange = function (event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function () {
var text = reader.result;
var lines = text.split(',');
for (var line = 0; line < lines.length; line++) {
let elements = lines[line].split(':');
localStorage.setItem(elements[0], elements[1]);
}
};
reader.readAsText(input.files[0]);
};
});
It will insert the elements in the localStorage as you described. For example: key = step1chapter1Question1 and value = U2FsdGVkX1+/Sv61L69bLvQGTkf1A9Uy4jgJ3KZTkzI=

Reading excel file into array using javascript

I'm trying to read an excel file and create a multidimensional array in javascript with it.
The excel file will look like:
AA11 AA22 AN65
AB11 AB22 AN64
...
I need it to create an array that looks like:
[
[AA11, AA22, AN65],
[AB11, AB22, AN64]
]
So far, I've been able to bring up a file selection window, and I believe it's reading the file, I just think it might not be putting the data into the array correctly. This is what I have so far:
<script type="text/javascript">
$(function () {
$("#input").on("change", function () {
var excelFile,
var array = [[],[]];
fileReader = new FileReader();
$("#result").hide();
fileReader.onload = function (e) {
var buffer = new Uint8Array(fileReader.result);
$.ig.excel.Workbook.load(buffer, function (workbook) {
var column, row, newRow, cellValue, columnIndex, i,
worksheet = workbook.worksheets(0),
columnsNumber = 0,
gridColumns = [],
data = [],
worksheetRowsCount;
while (worksheet.rows(0).getCellValue(columnsNumber)) {
columnsNumber++;
}
for (columnIndex = 0; columnIndex < columnsNumber; columnIndex++) {
column = worksheet.rows(0).getCellText(columnIndex);
gridColumns.push({ headerText: column, key: column });
}
for (i = 1, worksheetRowsCount = worksheet.rows().count() ; i < worksheetRowsCount; i++) {
newRow = {};
row = worksheet.rows(i);
for (columnIndex = 0; columnIndex < columnsNumber; columnIndex++) {
cellValue = row.getCellText(columnIndex);
//newRow[gridColumns[columnIndex].key] = cellValue;
array[row,columnIndex] = cellValue;
}
window.alert(array[0][0]);
data.push(array);
}
</script>
Any help would be greatly appreciated.
Not sure what you're using to parse the Excel, is it IgniteUI ? For what it's worth, the free (community edition) of SheetJS, js-xlsx provides a few functions that produce exactly the output you needed, given the spreadsheet you provided.
The docs are a bit messy, but they are complete, the most interesting sections for this use-case are: Browser file upload form element under Parsing workbooks and XLSX.utils.sheet_to_json. You can run a test with the type of spreadsheet you provided in the code sample below:
$("#input").on("change", function (e) {
var file = e.target.files[0];
// input canceled, return
if (!file) return;
var FR = new FileReader();
FR.onload = function(e) {
var data = new Uint8Array(e.target.result);
var workbook = XLSX.read(data, {type: 'array'});
var firstSheet = workbook.Sheets[workbook.SheetNames[0]];
// header: 1 instructs xlsx to create an 'array of arrays'
var result = XLSX.utils.sheet_to_json(firstSheet, { header: 1 });
// data preview
var output = document.getElementById('result');
output.innerHTML = JSON.stringify(result, null, 2);
};
FR.readAsArrayBuffer(file);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.14.5/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="input" accept=".xls,.xlsx,.ods">
<pre id="result"></pre>
Here the full solution aditionally I've added a group by category function
to demostrante that we can apply functions to the json array.
(async() => {
const url = "./yourfile.xlsx";
const data = await (await fetch(url)).arrayBuffer();
/* data is an ArrayBuffer */
const workbook = XLSX.read(data);
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
const sheetValues = XLSX.utils.sheet_to_json(worksheet);
const groupByCategory = sheetValues.reduce((group, product) => {
const { category } = product;
group[category] = group[category] ?? [];
group[category].push(product);
return group;
}, {});
console.log(groupByCategory)
/* DO SOMETHING WITH workbook HERE */
})();

How to pass All Arrays in Google Script

I have a HTML File that upload a TSV File and display it in console as an array. here is the code.
document.getElementById('file').onchange = function(){
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
// Entire file
console.log(this.result);
// By lines
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
// By tabs
var tabs = lines[line].split('\\t');
for(var tab = 0; tab < tabs.length; tab++){
console.log(tabs[tab]);
}
}
};
reader.readAsText(file);
};
<input type="file" name="file" id="file">
now here is my code.gs
function doGet(e){
var html = HtmlService.createHtmlOutputFromFile("index");
return html;
}
My question is how can I pass the array from the html file to code.gs? maybe a sample Logger.log will be okay form me. My target here is to upload that array in google sheet. TYSM
How about following modification? When it sends the values on html to GAS, you can achieve this using google.script.run.
In this modifed sample, the array is sent to work() on GAS, and the array data is imported to Spreadsheet.
Modified Script :
index.html
document.getElementById('file').onchange = function(){
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
// Entire file
console.log(this.result);
// By lines
var ar = []; // <--- added
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
// By tabs
var tabs = lines[line].split('\t'); // <--- modified from '\\t' to '/t'
for(var tab = 0; tab < tabs.length; tab++){
console.log(tabs[tab]);
}
ar.push(tabs); // <--- added
}
google.script.run.work(ar); // <--- added
};
reader.readAsText(file);
};
code.gs
function doGet(e){
var html = HtmlService.createHtmlOutputFromFile("index");
return html;
}
function work(res){
var ss = SpreadsheetApp.getActiveSheet();
ss.getRange(1,1,res.length,res[0].length).setValues(res);
}
Input
a1 b1 c1
a2 b2 c2
a3 b3 c3
Output
If I misunderstand your question, I'm sorry.

reader.onload: Looping Jquery function

I was wondering if it is possible to get this right. I am using a Jquery cropping tool (cropit). I am trying to put multiple file inputs into several cropper instances at once. Unfortunately it doesnt work that well.
For example, if I upload three images, the first two croppers are empty and the last one gets one of the images randomly. Here is the function:
function handleCropit(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var count = counterCropit();
var reader = new FileReader();
reader.onload= function(e){ $('#image-cropper'+count).cropit('imageSrc', e.target.result);};
reader.readAsDataURL(file);
}
}
Figured it out!
function handleCropit(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var count = counterCropit();
var croper = $('#image-cropper'+count);
var reader = new FileReader();
reader.onload= (function (yo) {return function(e){ yo.cropit('imageSrc', e.target.result);}})(croper);
reader.readAsDataURL(file);
}
}

Is it possible to load a specific file type using Javascript?

I have a function that is loading a user selected file using the Javascript File API, but I want to limit the type of file that can be loaded. Is this possible and how do I go about doing it? So for example, I only want the user to be able to load a DAT file. Here's my function loading the file.
function readFile(file){
var reader = new FileReader();
var holder;
var holderArray = [];
var fileArray = [];
reader.readAsText(file, "UTF-8");
reader.onload = function(){
file = reader.result;
file = file.split(/\s+/g);
formatFile(holderArray, 3, holder, file, fileArray);
for(var i = 0; i < 2; i++){
formatFile(holderArray, 1, holder, file, fileArray);
}
for(var i = 0; i < 2; i++){
formatFile(holderArray, 2, holder, file, fileArray);
}
var meh = file.length / fileArray.length;
for(var i = 0; i < meh; i++){
formatFile(holderArray, 5, holder, file, fileArray);
}
fileArray.pop();
plume = new Plume(fileArray[0], fileArray[4], fileArray[3]);
$("#eventDate").val(plume.dateTime);
$("#eventLat").val(plume.startLat);
$("#eventLon").val(plume.startLong);
$("#eventDictionary").val(plume.dict);
$("#eventSymbol").val(plume.symbol);
fileArray = fileArray.splice(5);
plume.graphic = fileArray;
}
}
$("#load").on("click", function(){
$("#eventNameInput").val("");
var selectedFile = $("#selectedFile");
selectedFile = selectedFile[0].files[0];
if(selectedFile){
readFile(selectedFile);
$("#fileDetails").show();
}
})
Sure. You can declare MIME type in "accept" attribute For example this input will upload images :
<input type="file" name="img" accept="image/*">
for .dat you can do this (.dat is unknown MIME type):
<input type="file" name="img" accept=".dat">

Categories

Resources