Basically, I want to upload ONLY a CSV file via Javascript or jQuery.
I want to try and do this without any PHP involved.
I need to use a HTML upload form, and then save only it's contents to a multidimensional array or a string.
I do not need to save the uploaded file to the server, I just need to save it's contents to a string as stated.
I have looked far and wide online, yet everything involves PHP.
Is this possible with just Javascript or jQuery?
Thanks in advance
This uses a library I wrote and released under the GPLv3 License: html5csv
The example below uploads a CSV file into the browser, where it is available as an array of arrays.
The library supports various block operations, such as make a table, edit, plot, fit, call a function, save in browser session storage or local storage.
JSFIDDLE
html
Choose a CSV file to load into the application:
<input id='foo' type='file'>
<hr />
js (requires jQuery and html5csv.js)
CSV.begin('#foo').
table('output', {header:1, caption:'Uploaded CSV Data'}).
go();
Here, go() can take a function callback
(e,D), where e will contain an error string or null, and D is an object that may contain D.rows[0][0],...,D.rows[n-1][m-1] for a n x m matrix of data. Row 0 may be a header row.
Asynchronicity is used, in fact enforced in places. So beware that like AJAX, this code will return immediately to the subsequent line, and is best read as setting up a workflow of what to do when the previous step becomes ready.
Saving/Restoring
You can save data into the user's browser localStorage object with .save('local/someKey'). somewhere in the workflow, and data existing in the array at that point will be stored in HTML5 local storage (perhaps even compressed if you include the LZString library as documented), until the browser user deletes it.
Then in the same page or another page on the same web site you can get the data back out with CSV.begin('local/someKey')...
Using the data
You should put any code you want to use the data into a function that can fit either the callbacks expected by html5csv's call or go as documented on the html5csv site.
The jQuery CSV plugin can use client-side file handling (no need for server-side script like PHP):
https://code.google.com/p/jquery-csv/#Client-Side_File_Handling
You can use plugin which allow you to parse CSV into Array.
http://code.google.com/p/jquery-csv/
Features
Convert a CSV String to an array
Convert a multi-line CSV string to a 2D array
Convert a multi-line CSV string to an array of objects (ie header:value pairs)
Convert an array of values to CSV (under development)
Convert an array of objects to CSV (under development)
Hooks/Callbacks to extend the default parsing process
Customizable delimiter (default: ") and separator (default: ,) characters
Node.js support (ie CommonJS importing and async callback support)
To do the upload, you need to be able to read the file off the disc. You can do this with the HTMl5 File API. I'm sure there are jQuery libraries to simplify this, but that's the underlying tech.
Someone else posted a question (and solution) on how to do that with jQuery: html5's file api example with jquery?
Once you've got access to the file in the browser, use a CSV library to work with it.
Related
I have a script which reads a file line by line, generate an object with some fields from certain lines and now I want to put that generated object into a CSV file.
How can I do the following:
From the script itself generate a CSV file
Give initial fields (headers) to the file
Update that file line by line (add to the file one line at a time)
Some clarifications, I don't know the size of the CSV in advance, so the file must by dynamically changed.
Thanks in advance.
Looking at what you have said:
From the script itself generate a csv file
Have a look at node-csv-generate which lets you generate csv strings easily
Give initial fields (headers) to the file & 3. Update that file line by line (add to the file one line at a time)
Check out the node-csv-generate stream functionality to write individually line by line (i.e. inital headers first)
Now since you said you need to run it locally, I would recommend Rhino if just using JS but if node.js is required then check out Rhinodo. These will let you run the program locally on the JVM basically (you could call the JS from within Java if you wanted to).
To export the CSV file there are plenty examples online this SO thread being one... i.e.
var encodedUri = encodeURI(csvContent);
window.open(encodedUri);
Where csvContent is the complete string of your csv. I am not sure how supported this is on Rhinodo, but I'm pretty sure it'll all work on Rhino.
If this is intended to be a purely desktop based application, I would look at using Java (or your preferred language Python or C# might be nicer depending on what you are used to :-) ) rather than JS if everything needs to be local and it intends on being widely used. That way you have a much cleaner interaction with the OS and a lot more control.
I hope this helps!
I have a very large array with thousands of items
I tried this solution:
Create a file in memory for user to download, not through server
of creating an anchor
text file
~~JSON.stringify on the array caused the tab to freeze~~ Correction: Trying to log out the result caused the tab to freeze, stringify by itself works fine
The data was originally in string form but creating an anchor with that data resulted in a no-op, I'm assuming also because the data was too big, because using dummy data successfully resulted in a file download being triggered
How can I get this item onto my filesystem?
edit/clarification:
There is a very large array that I can only access via the the browser inspector/console. I can't access it via any other language
Javascript does not allow you to read or write files, except for cookies, and I think the amount of data you are using exceeds the size limit for cookies. This is for security reasons.
However languages such as php, python and ruby allow the reading and writing of files. It appears you are using binary data, so use binary files and write functions.
As to the choice of language : if you already know one use that, or whichever you can get help with. Writing a file is a very basic operation and all three languages are equally good. If you don't know any of these languages you can literally copy and paste the code from their websites.
I am newbie working on a 100% js prototype. It consist of 3 docs: an html page full of xml tags, a small dictionary in a text file format, and a js file with jquery.
The js needs to parse the xml tags (no problem here) and look into the mini-dictionary list for available translations.
Which is the best way to implement the mini-dictionary list. (No more than 50.000 records). Is there a way to load the list into a memory database and access it from js? Which is the usual path to take in this case? What is the simplest and machine-independent way to do this?
Any directions as to where should I research are greatly appreciated.
I would suggest encoding mini-dictionary with JSON data format, and then using AJAX to get that file and parse it. But then you are risking someone will just copy whole dictionary and steal your work.
That is, if you are not using server side language, like PHP. If you are using it, then just store everything into database and request just specific words with AJAX.
I once again need to do something that sounds simple but is infact frustratingly evading me.
On my company's intranet site we have a large table of data that has a javascript filter applied to it so that managers and other interested parties can quickly locate the rows that are relevant to them. The filter I am using can be found at http://tablefilter.free.fr/ .
My issue arises when I need to have a button to export the filtered results to Excel so that the managers can access the data offline. There are many straight forward options for exporting the HTML table to excel but I have been unable to figure out how to get JUST the filtered results to export. (Note: This intranet site will only be accessed via IE)
There is a function as part of the javascript table filter, GetFilteredData(), that will grab the filtered data cells and input these into an array, i think called filteredData[]. This array is formated as such: [rowindex,[value1,value2,value3...]].
So how do I get this array into an Excel or csv file? Again, this will be accessed only by IE so activeX objects and controls are acceptable.
Also I should probably note that I cannot use server-side technologies so please limit your responses to the confines of HTML, javascript and activeX. Thanks!
FYI: DataTables has a nice plugin called TableTools which can export table to csv on client-side. It's achieved using Flash. If you are satisfied with the filter of DataTables, I think this would be a good solution.
http://www.datatables.net/extras/tabletools/
If you are using IE starting at version 8, you can use data: URLs. Just generate the URL and point the borwser there using location.href. The data in CSV can be generated by javascript and base64 encoded.
You might want to consider an approach that relies on string manipulation.
Once you have this array, you can turn it into a JSON string. Try this popular lightweight library (json2.js):
https://github.com/douglascrockford/JSON-js
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
You should have something like
var dataString = '["rowindex",["value1","value2","value3"]]'
At this point you could use some regex replacement on the string to format it to either style.
A page on a site I use is holding some of my data hostage. Once I have logged into the site and navigated to the right page, the data I need is in the array eeData[] - it is 720 elements long (once every 2 minutes of a given day).
Rather than simulate the requests to the underlying stuff json supplier and since its only once a day, I am happy to simply develop a bookmarklet to grab the data - preferably as a XML or CSV file.
Any pointers to sample code or hints would help.
I found a bookmarklet here that is based on this script that does part of this - but I am not up to speed on any potential JS file IO to see if it is possible to induce a file "download" of the data, or pop it opn in a new window I can copy / paste.
What are the datatypes of the objects in eeData? Converting arbitrary Objects to a useful serialisation isn't doable in the general case; you would have to write your own JS function to inspect the objects and pick out the properties you wanted to serialise to whatever format.
But if they're simple Arrays and Objects used as mappings, probably the quickest way to export them would be JSON. Use a browser with native JSON (eg. Firefox 3.5, IE8) and this bookmark:
javascript:document.body.innerHTML='<textarea id="t"></textarea>';void(document.getElementById('t').value=JSON.stringify(eeData));
then copy-and-paste the data out of the textarea.