How to upload and process CSV File using ExtJS Client Side - javascript

I am trying to Upload a CSV File containing IP addresses using Ext-js and have it processed and converted into a JSON Object on the client-side before sending it to the server to be added to the repository.
I need to parse the CSV, convert it into a JSON Object and then add the information to a Data Store- but I'm terribly stuck.
Are there any existing libraries that can help achieve this?
I am looking at avoiding jQuery/HTML5. Is there a way we can do it exclusively using Javascript / Extjs?
I tried going through a lot of examples- but most of them use jQuery/HTML5 API/ Papa-Parse or prefer doing it server side.
My 'Upload' Button handler function looks like this:
handler: function () {
var file = Ext.getCmp('form-file-win').getEl().down('input[type=file]').dom.files[0];
var reader = new FileReader();
var importedAddresses=[];
reader.onload = function (oFREvent) {
importedAddresses=oFREvent.target.result;
};
reader.readAsText(file);
this.dataStore.add({
id: '',
name: 'Imported from CSV',
});
win.close();
}

Unfortunately there is no way to access the content of the file on the client side.
You have two options:
You either post the file to the server and process it serves-side and give a json response for your javascript
Or you need to use HTML5 to access a local file. Here is a tutorial on how to do that: local file processing

Related

How to set a variable's value to uploaded file json data in angularjs?

I'm new to angularJS. I want to upload a JSON file using
<input type="file"onchange="angular.element(this).scope().uploadFile(this.files)"/>
and I am trying to access its data in the controller like this:
$scope.uploadFile = function(files) {
$scope.jsonData = files[0].data;
};
But I get an undefined in my variable. I have to use this variable to populate various other fields on the website. Kindly help me how to access the data of the input file uploaded.
You need use FileReader API.
The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer.
Its method FileReader.readAsText()
The readAsText method is used to read the contents of the specified Blob or File.
Note: Here is an example, It works in Modern browsers
$(document).ready(function() {
$('#file').change(function(e) {
var reader = new FileReader();
reader.onload = function(e) {
console.log(e.target.result);
//if you want in JSON use
//var json = JSON.parse(e.target.result)
}
reader.readAsText(this.files[0]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file" name="file" />
Just Another way to go around... if you don't want to use the FileReader and manually parse the text using JSON.parse and also wrapping it around a try/catch in case of wrong format
// simulate a file `file = files[0]`
var file = new Blob(['{"hello": "world"}'])
new Response(file).json().then(
json => console.log(json),
err => console.error("invalid json data")
)
Or with the help of Screw-FileReader
// simulate a file `file = files[0]`
var file = new Blob(['{"hello": "world"}'])
file.json().then(json => console.log(json))
<script src="https://cdn.rawgit.com/jimmywarting/Screw-FileReader/master/index.js"></script>
(Posted solution on behalf of the OP).
Thank you #Satpal I solved it using fileReader.readAsText() and JSON.parse().

How can I unzip the zipped file using AngularJs?

I want to unzip the zipped file while downloading the file using AngularJS.
I am trying with the following code,
For eg:
<a download="My_File.PNG" target="_self" ng-href="Path of the zip file/My_File.PNG.zip">My_File.PNG</a>
How can I download the actual file My_File.PNG from My_File.PNG.zip in the browser?
You can't do it from angular directly, but you can call use the JSUnzip library which you can call from your angular controller https://github.com/augustl/js-unzip
var myZip = ... // Get it with an XHR request, HTML5 files, etc.
var unzipper = new JSUnzip(myZip);
unzipper.isZipFile(); // true or false
unzipper.readEntries(); // Creates "entries"
unzipper.entries; // Array of JSUnzip.ZipEntry objects.
It's a little bit late, but the problem is in the angular request. You have to pass a special parameter, as in
$http.get('...', { responseType: "arraybuffer" }).success(successfunc);
and then proceed with the unzip. Search for this...

using and storing json text in JavaScript

I'm making a 2D, top-down Zelda-style web single player rpg...
I'd like to store dialog in JSON format...
Currently I'm getting the json as an external javascript file. The json is stored as such in js/json.js:
function getJson() {
var json = {
"people" :
[
{//NPC 1 - rescue dog
etc...
Then I use it in my main game javascript file as such <script src="js/json.js"></script>..`
var json = getJson();
Then use it as such:
Labels[index].text = json.people[index].dialogs.start.texts[0];
Does it matter if I keep the json as a js file in a javascript function? Or should it be stored as a .txt file then parsed?
Thanks!
It does not matter but JSON data is also JavaScript so store it as .js and later on you can add more data related functions to it if needed, btw your data file already has a getJSON function so it doesn't make sense to store it as .txt
On the other hand if an API is serving this data it need not have any extension at all.
It's better off storing the data in pure JSON format and retrieving it via jQuery.getJSON() or an XMLHttpRequest, if you're using vanilla JavaScript. Otherwise, it looks like you're adding getJson() to the global scope, which may result in a conflict if you have another getJson() defined elsewhere.
So you could have a dialog.json that looks almost the same as what you have now, just without the unnecessary getJson() function:
{
"people" :
[
{//NPC 1 - rescue dog
...
}
]
}
If you choose to use jQuery:
var dialog;
$.getJSON('json/dialog.json', function(data) {
dialog = data;
// Asynchronous success callback.
// Now dialog contains the parsed contents of dialog.json.
startGame();
});
Keeps your data separate from your logic.

Forcing Backbone to save an attribute as a file

Is there a way to use Model.set and Model.save in a way that will force Backbone to send the data to the server as a file (as if you were submitting a form with an <input type="file"> tag?
The short answer is no. The long answer is, sort of.
This doesn't really have anything to do with Backbone and instead is about being able to AJAX a file in the browser. The solution is to use the File API from HTML 5. Below is an example of how you would do that with a Backbone model.
Let's assume we have a User model and we want to save an avatar file on that model.
// Backbone Model JS
User = Backbone.Model.extend({
readAvatar : function (file, callback) {
var reader = new FileReader(); // File API object for reading a file locally
reader.onload = (function (theFile, self) {
return function (e) {
// Set the file data correctly on the Backbone model
self.set({avatar_file_name : theFile.name, avatar_data : fileEvent.target.result});
// Handle anything else you want to do after parsing the file and setting up the model.
callback();
};
})(file, this);
reader.readAsDataURL(file); // Reads file into memory Base64 encoded
}
});
// Somewhere in your view JS
this.$("input[type='file']").change(function (event) {
var file = e.originalEvent.target.files[0];
userModel.readAvatar(file, userModel.save);
});
// HTML
<form><input type="file" name="avatar"/></form>
Now on your back end you need to handle the file coming through as Base64 encoded data.
A couple of warnings:
If you need extensive browser support then this solution probably won't work for you.
Base64 encoding a file is going to increase the amount of data sent over the wire by about 30%.

how to export csv file with filename

I want to export the exist data into csv file. I try to use this code:
var uriContent = "data:text/csv;charset=utf-8," + encodeURIComponent(data);
var myWindow = window.open(uriContent);
myWindow.focus();
it works but I can design filename. I can only get the dialog with name like "MVeAnkW8.csv.part" which I don't know where the name come from.
How can I assign filename in the first dialog? Thanks in advance.
update:
I am now using rails. Actually I have a method in server side names export_to_csv. In end of this method, I use code like that:
send_data(csv_string,
:type => 'text/csv; charset=utf-8;',
:filename => "myfile.csv")
It works and I can specify the file name.
For now, I want to use ajax to get more csv files(that is the reason why I want to use javascript, because a normal http request can only get one file to be downloaded).
I use js code like that:
$.post("export_to_csv",
function(data) {
var uriContent = "data:text/csv;charset=utf-8," + encodeURIComponent(data);
var myWindow = window.open(uriContent);
myWindow.focus();});
It get the data from server side and I try to transfer it into csv. I can get a file but can't specify the file name.
As I know, you can specify the filename only in chrome 14+.
Take a look at this question: Is there any way to specify a suggested filename when using data: URI?
Update!
If you want to download multiple csv files "at once", you can zip them together, or save each file on the server separately (each file now has a url that points to it - if you place them inside the 'www' folder).
Then send the file names and their path/url to the client via ajax (use a json encoded list for example).
In the ajax callback function: take the list of the files and open each file-url in a separate popup.

Categories

Resources