Error reading binary file - javascript

I'm trying to read a binary file in JavaScript.
However, it is not returning anything. What's wrong with the command below?
function autenticarbiometria() {
var fileInput = document.getElementById('fileInput');
var file = fileInput.files[0];
var reader = new FileReader();
var campo = "";
var status = "f";
filereader.onload = function(e) {
var campo = reader.result;
document.getElementById('template').value = campo;
alert("CAMPO TAMANHO --> " + campo.length);
}
reader.readAsArrayBuffer(file);
...

An ArrayBuffer cannot be set as string. You need to convert the content to a string, or a Base-64 / hex representation if the binary data is not printable.
For text you can use the new TextDecoder object (may need polyfill in some browsers).
Example
var td = new TextDecoder("utf-8"); // or use utf-16 etc. depending on what you expect
var txt = td.decode(campo); // pass in the ArrayBuffer
Now txt can be set as string source for your element (if readable).
Also note that you have a local var of campo which overrides the parent var campo.

Should it not be:
var fr = new FileReader;
var txt = fr.readAsText(document.getElementById('fileInput').files[0]);
fr.onloadend = function(r){
console.log(r);
}

Related

How to Upload an Excel File in SAPUI5?

so I have this app where I upload a csv file using FileUploader. However now my requirement is to also allow excel files. The problem is that FileUploader doesn't support excel as it reads garbage. This is my attempt at parsing an excel file based on this example http://oss.sheetjs.com/js-xlsx/
Code:
var fileUpload = this.getView().byId("fileUploader");
var domRef = fileUpload.getFocusDomRef();
var file = domRef.files[0];
var XLSX = new ExcelPlus();
XLSX.createFile(["CT_MAIN"]);
var reader = new FileReader();
reader.onload = function(e) {
var strCSV = e.target.result;
var arr = String.fromCharCode.apply(null, new
Uint8Array(strCSV));
// var arr = fixData(strCSV);
console.log('data');
console.log(arr);
var workbook = XLSX.read(arr, {type : 'base64'});
console.log('output');
console.log(workbook);
//var output = toCsv(workbook);
//each one of the rows in the csv file
//var rows = arr;//strCSV.split("\n");
var rows = arr.split("\n");
.....
};
//reader.readAsText(file);
reader.readAsArrayBuffer(file);
//reader.readAsBinaryString(file);
If I upload a csv file using this code everything works fine. If I use an excel file I get the following
[1][Content_Types].xml ¢ [1]( [1]¬”ËNÃ0E÷HüCä-Jܲ#5í‚Ç Q>Àēƪc[žiiÿž‰ûB¡ j7± ÏÜ{2ñÍh²nm¶‚ˆÆ»R‹ÈÀU^7/ÅÇì%¿’rZYï #1__f›˜q·ÃR4DáAJ¬h >€ãÚÇV ßƹ
ªZ¨9ÈÛÁàNVÞ 8Ê©ÓãÑ Ôji){^óã-I‹"{Üv^¥P!XS)bR¹rú—K¾s(¸3Õ`c[1]Þ0†½
ÝÎß»¾7 M4²©ŠôªZÆk+¿|\|z¿(Ž‹ôPúº6 h_-[ž#!‚ÒØPk‹´¬2nÏ}Ä? £LËð Ýû%á ÄßdºždN"m,à¥ÇžDO97‚~§Èɸ8ÀOíc |n¦Ñä Eøÿ ö éºóÀBÉÀ!$}‡íàÈé;{ìÐå[ƒîñ–é2þÿÿ
what am I doing wrong, or what am I missing here?
Edit: after doing var workbook = XLSX.read(arr, {type : 'base64'}); I get null for both file types. The above garbage log comes from console.log(arr);
Since you are getting the file from the domRef you wouldn't need ExcelPlus. You just need to read the file as a binary string using xlsx. You will have to include the xlsx.full.min.js in your script.
var fileUpload = this.getView().byId("fileUploader");
var domRef = fileUpload.getFocusDomRef();
var file = domRef.files[0];
//var XLSX = new ExcelPlus();
//XLSX.createFile(["CT_MAIN"]);
var reader = new FileReader();
var name = file.name;
reader.onload = function (e) {
var data = e.target.result;
var workbook = XLSX.read(data, { type: 'binary' });
var result = {};
workbook.SheetNames.forEach(function (sheetName) {
var rObjArr = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
if (rObjArr.length > 0) {
result[sheetName] = rObjArr;
}
});
var output = JSON.stringify(result, 2, 2);
console.log('output');
console.log(output);
};
reader.readAsBinaryString(file);

How to grab everything but the first line from .txt with JavaScript FileReader?

I have text file and I would like to grab everything but my first line. Also I would like to check how many columns have each of my rows. How that can be done with JavaScript File Reader? I have used code bleow for reading just the first row:
var fileExist = $('#fileUpload')[0];
var reader = new FileReader();
var file = fileExist.files[0];
reader.onload = function(e) {
var text = reader.result;
var firstLine = text.split('\n').shift();
var columnNames = firstLine.split('\t');
console.log(columnNames);
}
reader.readAsText(file, 'UTF-8');
Just get rid of the first line with pop() and then iterate through the Array.
var fileExist = $('#fileUpload')[0];
var reader = new FileReader();
var file = fileExist.files[0];
reader.onload = function (e) {
var text = reader.result;
var allLines = text.split('\n');
// Print the colomn names
console.log(allLines.pop().split('\t'));
// Get rid of first line
allLines.pop();
// Print all the other lines
allLines.forEach(function (line) {
console.log(line.split('\t'));
});
}
reader.readAsText(file, 'UTF-8');

How to checksum the file to be uploaded with javascript?

I want to checksum the files at browser side before uploading, then checksum and compare at server side to make sure the consistent. But how can I get the pure binary data of the file and checksum it? I tried the way below, but doesn't work:
let fileSelect = document.getElementById('file')
let files = fileSelect.files
let file = files[0]
var r = new FileReader();
r.onload = function(){ console.log(r.result); };
r.readAsArrayBuffer(file);
var file_sha1 = sha1(r.result)
The library you are using seems to support string input only.
Find a library support binary input. Eg. js-sha1. And you should hash it in the callback.
var reader = new FileReader();
reader.onload = function (event) {
var file_sha1 = sha1(event.target.result)
};
reader.readAsArrayBuffer(file);

Javascript split blob as strings

Say you parse a text file with fileReader:
function show() {
var file = document.getElementById('myFile');
var data = file.files[0];
var fileRead = new FileReader();
fileRead.onload = function() { document.getElementById('out').appendChild(document.createTextNode(' ' + fileRead.result)) }
fileRead.readAsText(data);
}
How do you split a blob object (raw data) with the split function which works only on strings?
If I convert the blob to string and then call readAsText it reasonably complains that the data variable (containing text) is not a blob object.
So, basically I want to use the split function on the blob text object.
You can just do it in the onload callback.
var file = document.getElementById('myfile');
var data = file.files[0];
var var fileReader = new FileReader();
fileReader.onload = function() {
let strings = fileReader.result.split(' ');
strings.forEach(function(string) {
//Your code here
})
}
fileReader.readAsText(data)
If you want blob objects representing each split string, you would have to build the blob objects in the foreach loop.

HTML5 FileReader + WebSQL

Ist it possible to parse a csv-file with FileReader an write it a WebSql Table?
The FileReader.readAsText() method will give you a string from the file which you can then split() to get the lines and csv cells. Check out readAsText() for more details and try pasting the following in to the interactive example:
<script id='csv' type='text/plain'>
apple,1,$1.00
banana,4,$0.20
orange,3,$0.79
</script>
<script>
// Use a Blob to simulate a File
var csv = document.getElementById('csv').textContent.trim();
var file = new Blob([csv]);
var reader = new FileReader();
reader.onload = function(event){
var reader = event.target;
var text = reader.result;
var lines = text.split('\n');
lines.forEach(function(line) {
var parts = line.split(',');
// process the cells in the csv
console.log(parts[0], parts[1], parts[2]);
});
};
reader.readAsText(file);
</script>
Yes, that should not be a problem at all :)
Just use FileReader.readAsText() to grab the csv file content, and from there it should be a breeze
With Screw-FileReader
// Use a Blob to simulate a File
let blob = new Blob([
`apple,1,$1.00
banana,4,$0.20
orange,3,$0.79`
])
blob.text().then(text => {
var lines = text.split('\n')
for (let line of lines) {
let parts = line.split(',')
// process the cells in the csv
console.log(parts)
}
})
<script src="https://cdn.rawgit.com/jimmywarting/Screw-FileReader/master/index.js"></script>

Categories

Resources