I am completely new to this.The solutions that I am getting from internet is reading the file and displaying as it is, but I want to read the file line by line.
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
console.log(lines[line]); }
with \n you can split a file at his linebreaks.
Your question was very vague but this is the solution when you want to output a file line by line.
To get this into Context:
First we need to input a file, we can achieve this via HTML:
<input type="file" name="file" id="filename">
Now create a js function to grab this file:
document.getElementById('filename').onchange = function(){
// declare file variable
var filevar = this.files[0];
//the Reader:
var datareader = new FileReader();
reader.onload = function(progressEvent){
};
I already included a FileReader, as you can see
Now you can combine this to a full function:
document.getElementById('filename').onchange = function(){
var filevar = this.files[0];
var datareader = new FileReader();
reader.onload = function(progressEvent){
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
console.log(lines[line]);
}
};
datareader.readAsText(filevar);
};
This is a bit tutorialish so sry, but i guess it helps more then just Code.
Related
I tried to upload Multiple files and wants to read the content of the file for encrypt the data.
I can able to read the single file properly , but I can't do it while upload multiple files am getting error reader is busy.
If I create new Filereader while onloadend it gives me null value of content.
React JS - sample code:
let reader = new FileReader();
class FilReaderComp extends Component {
constructor(props) {
super(props);
this.state = {
}}
upLoadFileFolderFunc(e){
e.preventDefault();
let fileitemsList = e.target.files;
for (let i = 0; i < fileitemsList.length; i++) {
let fileitems = fileitemsList[i];
reader.onloadend = this.handleFileRead;
reader.readAsText(fileitems);
}
}
handleFileRead = (e) => {
const content = reader.result; here am reading content of the file
//here doing my function after getting content
}
render(){
return(
<input type="file" className="custom-file-input" style={{display:"hide"}}
onChange={this.upLoadFileFolderFunc} multiple/>
);}
export default withRouter(FilReaderComp);
Try wrapping your onload function in another function and enclose the filereader in the loop. Here the closure gives you access to each file being processed in turn via the variable f:
function openFiles(evt){
var files = evt.target.files;
for (var i = 0, len = files.length; i < len; i++) {
var file = files[i];
var reader = new FileReader();
reader.onload = (function(f) {
return function(e) {
// Here you can use `e.target.result` or `this.result`
// and `f.name`.
};
})(file);
reader.readAsText(file);
}
}
I'm working on a app that use cordova-plugin-media to record and audio file, and now I want to encode this file to base64 string, for now I can locate the file but when I try to encode it I get this :
"{"$$state":{"status":0}}"
Here is my code
audio.stopRecord();
audio.play();
if(device.platform == "iOS")
{
var path = cordova.file.tempDirectory;
}
else if(device.platform == "Android")
{
var path = cordova.file.externalRootDirectory;
}
var filename = name + extension;
var filepath = path + filename;
console.log(filepath);
console.log(JSON.stringify($cordovaFile.readAsDataURL(path, filename)));
file path : file:///storage/emulated/0/tPUhcxUKhmLUrWK3Qkqhc69OxeEIWyYrhEB0he9OwM0ffmjY2OUh3TLbFTsApdpIpjxyuC2wouyCs6m7uvdOCHCMiw9mbLMGYM25.mp3
Can any one help me with this??
Thanks
readAsDataURL needs a file object, it won't work with a string path.
Give the following code a try, working on iOS and Android
window.resolveLocalFileSystemURL(path, function(fileEntry) {fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
var base64String = evt.target.result;
};
reader.readAsDataURL(file);
});}, function(e){console.log("error:" + JSON.stringify(e));});
I am using datatables to print the csv file data. The CSV file consists of data .this is an exmple data file.
name,city,category,discount
surya,gnt,all,10%
surya,gnt,all,10%
surya,gnt,all,10%
surya,gnt,all,10%
surya,gnt,all,10%
I want to skip first line of data . How to stop displaying th first line in my datatable. And my code is`
//saving csv file to firebase
$('#save-csv').bind('click', function() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
var file = document.getElementById('files').files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event){
var csv = event.target.result;
var data = $.csv.toArrays(csv);
var csvObj = {}
for(key in data){
csvObj[key] = {};
csvObj[key].name = data[key][0];
csvObj[key].city = data[key][1];
csvObj[key].category = data[key][2];
csvObj[key].discount = data[key][3];
}
console.log(csvObj);
$scope.csvStores.stores = csvObj;
$scope.csvStores.$save().then(function(res){
console.info(res);
}).catch(function(err){
console.error(err);
});
$("#myModal").modal("hide");
swal(
'Saved',
'Successfully Saved',
'success'
)
}
}else {
}
});
Before you iterate over your data you should somehow remove/skip the first line.
In my opinion it is better to remove, cause if you would like to use later this array, then you have to skip again.
I have two ideas:
before the iteration call:data = data.shift();
based on this: http://www.w3schools.com/jsref/jsref_shift.asp
This will remove the first element.
Or if you are using lodash, than you can easily call data = _.tail(data); based on this: https://lodash.com/docs/4.16.4#tail
I'm using the FileReader Object in combination with xlsx.js to import data from an Excel-Sheet into my AngularJS Web-App.
The function never gets ended, so I need to continue the script manually by invoking an empty dummy function check(){} manually by clicking on a button to continue my script. I don't know, why the script behaves like that.
Code of my controller:
$scope.fileChanged = function(files) {
var i,f;
f = files[0];
reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
var workbook = XLSX.read(data, {type: 'binary'});
formData.data.teams = XLSX.utils.sheet_to_json(workbook.Sheets['latusch']);
var sheet_name_list = workbook.SheetNames;
var worksheet = workbook.Sheets['latusch'];
var result = {};
workbook.SheetNames.forEach(function(sheetName) {
var roa = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
if(roa.length > 0){
result[sheetName] = roa;
}
});
reader.readAsArrayBuffer(f);
}
readAsArrayBuffer is inside the onload callback, so it will not be called.
Remove it from the callback.
I have a streamer from server(SOAP) with different type of files, and i what seve it in physical storage.
I try this code but i only create file with my string.
api.getFile(function(fileString) {
var original = 'Appcelerator';
var decoded = Ti.Utils.base64decode(fileString);
var Settings = Titanium.Filesystem.getFile(Titanium.Filesystem.tempDirectory, 'Settings');
var newFile = Titanium.Filesystem.getFile(Settings.nativePath, 'Settings.pdf');
newFile.createFile(decoded);
// Ti.API.info('newfile: '+newFile.read());
});
}
}
try this one..
var original = 'Appcelerator';
var decoded = Ti.Utils.base64decode(fileString);
var Settings = Titanium.Filesystem.getFile(Titanium.Filesystem.tempDirectory, 'Settings');
Settings.createDirectory();
var newFile = Titanium.Filesystem.getFile(Settings.nativePath, 'Settings.pdf');
newFile.write(decoded);