HTML5 File Reader failed to add multiple files and only adding one file from the list - html

I want to add three files simulteneously.Files with extension kml,kmz and csv.
When I select all three files and click open I get all three files in FileList.
But only one file is getting added on map.If I add individual file i.e. one by one it works fine. reader onloadend event is fired 3 times.But all the time it adds only one of the three files.
function handleFileSelect(evt) {
var files = evt.target.files; // FileList
for (var i = 0; i < files.length; i++) {
f = files[i];
fileExtension = f.name.split('.').pop();
if(fileExtension != 'kml' && fileExtension !='kmz' && fileExtension != 'csv'){
alert('Unsupported file type ' + f.type + '(' + fileExtension + ')');
return;
}
var fileReaderkmlcsv = new FileReader();
fileReaderkmlcsv.readAsText(f);
fileReaderkmlcsv.onloadend =loadend;
} //- end for loop } //handleFileSelect

The problem was asynchronous code execution in javascript.
Here is the answer-
Asynchronous execution in javascript any solution to control execution?

Related

Correct way to signal stream complete

I've created a function to pipe data into a file and output individual files for each line of data. However, there are 35K lines of data to compile and although the code below signals "done" after about 5 mins, the files are still processing. I can't start the next function until this one is completed so I need to know when it has actually finished.
function createLocations(done) {
if (GENERATE_LOCATIONS) {
for (var i = 0; i < locations.length; i++) {
var location = locations[i],
fileName = 'location-' + location.area.replace(/ +/g, '-').replace(/'+/g, '').replace(/&+/g, 'and').toLowerCase() + '-' + location.town.replace(/ +/g, '-').replace(/'+/g, '').replace(/`+/g, '').replace(/&+/g, 'and').toLowerCase();
gulp.src('./templates/location-template.html')
.pipe($.rename(fileName + ".html"))
.pipe(gulp.dest('./tmp/'));
}
}
done();
console.log('Creating '+locations.length+' Files Please Wait...');
}
The function runs for a further 15mins after it has signalled done. Appreciate any help to detect the actual completion of the function.
Many thanks!

How to convert a json object into .csv file and how to export using Ionic 2 + angular 2?

I'm using a function in my angular 2 application to convert and export a JSON data into .CSV. The below is my function and is working fine in angular 2 application
(web). The Same I tried to use in mobile app which I developed using Ionic 2, it is not working in mobile app. Is there any way to do this?
Thanks!
saveAsCSV() {
let sampleJson : any = [{name:'ganesh', age:'24'},{name:'ramesh', age:'24'},{name:'suresh', age:'24'}]
this.saveData = [];
let a = document.createElement("a");
a.setAttribute('style', 'display:none;');
document.body.appendChild(a);
let csvData = ConvertToCSV(sampleJson);
let blob = new Blob([csvData], { type: 'text/csv' });
let url= window.URL.createObjectURL(blob);
a.href = url;
a.download = 'sample.csv';
a.click();
}
ConvertToCSV(objArray) {
let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
let str = '';
let row = "";
for (let index in objArray[0]) {
//Now convert each value to string and comma-separated
row += index + ',';
}
row = row.slice(0, -1);
//append Label row with line break
str += row + '\r\n';
for (let i = 0; i < array.length; i++) {
let line = '';
for (let index in array[i]) {
if (line != '') line += ',';
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
Use "cordova-plugin-file" to export csv in Ionic 2.
https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/
If you see the following error -
code:1 message:"NOT_FOUND_ERR"
Add one of the following lines in config.xml to resolve it.
<preference name="AndroidPersistentFileLocation" value="Internal" />
<preference name="AndroidPersistentFileLocation" value="Compatibility" />
As explained in the documentation of the plugin, you can use one of these two option to:
choose whether to store files in the internal
file storage location, or using the previous logic, with a preference
in your application's config.xml file. Without this line, the File plugin will use Internal as the
default. If a preference tag is present, and is not one of these
values, the application will not start.
If your application has previously been shipped to users, using an
older (pre- 3.0.0) version of this plugin, and has stored files in the
persistent filesystem, then you should set the preference to
Compatibility if your config.xml does not specify a location for the
persistent filesystem. Switching the location to "Internal" would mean
that existing users who upgrade their application may be unable to
access their previously-stored files, depending on their device.
If your application is new, or has never previously stored files in
the persistent filesystem, then the Internal setting is generally
recommended.

How to create a csv file of a form / table in ionic mobile app?

I am not able to find how I can create a csv or xls file of a table where data is inserted by users. I want a button that saves data as csv/xls file-format in ionic apps.
I have one form with a save button that saves data of the form in SQLite. I can also retrieve data in a table. Now, I want this table data to be saved in my ionic app. I used ng-csv, ng-sanitizer to handle this, this worked just fine in browser but the button does not fire in the application.
How can I handle that?
First of all,
Convert the data from json object to CSV.
function ConvertToCSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
Then just write the csv values as writeFile to externalRootDirectory.
$ionicPlatform.ready(function() {
$scope.exportCSV = function (data){
console.log(data);
var jsonObject = JSON.stringify(data);
console.log(jsonObject);
var finalCSV = ConvertToCSV(jsonObject);
console.log(finalCSV);
//alert('cordova.file.dataDirectory: ' + cordova); //I get [object Object]
// alert('cordova.file.dataDirectory: ' + cordova.file.dataDirectory); // I get file is undefined
$cordovaFile.writeFile(cordova.file.externalRootDirectory, 'data.csv', finalCSV, true).then(function(result){
alert('Success! Export created!');
}, function(err) {
console.log("ERROR");
})
}
});
And in the emulator or android device rootDirectory, which will be get by
Console.log(cordova.file.externalRootDirectory) or alert(cordova.file.externalRootDirectory)
Go to that directories and you will get your csv file, like this you can easily export the file with any kind of format.

File field - Append file list

I have made me a simple file field:
<input type="file" name="pictures_array[]" multiple accept="image/*" id="page_pictures_array" />
and some HTML5 File API code to list the files:
$('.page-form #page_pictures_array').change(function(evt) {
var file, files, reader, _i, _len;
files = evt.target.files;
console.log(files);
$('#file-list').empty();
for (_i = 0, _len = files.length; _i < _len; _i++) {
file = files[_i];
reader = new window.FileReader;
reader.onload = (function(file) {
return function(e) {
var src;
src = e.target.result;
return $("<li>" + file.name + " - " + file.size + " bytes</li>").prepend($('<img/>', {
src: src,
"class": 'thumb'
})).appendTo($('#file-list'));
};
})(file);
reader.readAsDataURL(file);
}
});
(cf. here)
However, since I expect my users to be very stupid indeed, I am sure they will choose one file, then click on the upload field another time to choose the next. However, the list of the <input type="file"> is reset each time with the newly chosen images.
How can I make sure the new files are appended to the <input>'s array so I don't get flooded with angry user comments?
I'm also looking for an answer to this, I think others already do that.
But if you look at the filelist W3 reference http://www.w3.org/TR/FileAPI/#dfn-filelist it says that its readonly....
Edit: It's a big code now, with some improvements, that make the copy/paste difficult. But I started to create one variable that saves all the tmp files.
var tmp_files = new Array();
Then when I add a new file I push the file to that array like this
tmp_files.push(file);
After all the insertions/removals (I have another var to save the deletions) when the user clicks to send the files I have this code that makes the formdata with the files I want
var data = new FormData(); var count = 0;
$.each(tmp_files, function(i, file){
if(del_files.indexOf(file.name)== -1){
data.append(count, file);
count++;
}
});
Then I just send the var data thru ajax and save them.
You can get them using $data = $_FILES;
Hope this helps you.

How can i append file using filewritersync?

I need to append file using HTML5 FileWriterSync, multiple blocks of data coming from server. I was tried to append but it was just writing a block of file only. Let's check my code.
var creator;
try {
fileEntry = fs.root.getFile(filename, {
create: creator
});
var byteArray = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++) {
byteArray[i] = data.charCodeAt(i) & 0xff;
}
var BlobBuilderObj = new WebKitBlobBuilder();
BlobBuilderObj.append(byteArray.buffer);
if (!creator) fileEntry.createWriter().seek();
fileEntry.createWriter().write(BlobBuilderObj.getBlob())
} catch (e) {
errorHandler(e);
}
fs has been initialised before, creator changes for appending file and I need to append file.
My problem is how can I call seek to start writing from the EOF.
seek() takes an integer value for the offset. You need to set it to the file's length to do an append:
var fw = fileEntry.createWriter();
fw.seek(fw.length);
It should be similar to the async case:
http://www.html5rocks.com/en/tutorials/file/filesystem/#toc-file-appending