how to export csv file with filename - javascript

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.

Related

How to save html form data in txt file using javascript

I have a html form. I want to store form data in another txt file using javascript.
For ex: I have a html form and store-data.txt file . when user fill the form and hit submit, so data stored in store-data.txt file.
How I will do this using javascript.
Javascript can`t save data on server. JS can save data on clients machine. Data on clients machine can be stored using cookie. But I feel, it isnt an aim. Store data from froms can server side apps, driven like php.
You can use filesaver.js library for a clean implementation or follow along with this codepen It is the quickest.
if you wanted to store input values assign all values in an object then JSON.stringify then throw it to this function to get text file of json
function createTextFile(str){
var file = new Blob([str])
anchor = document.createElement("a")
anchor.href = URL.createObjectURL(file)
anchor.download = "fileName"
anchor.click()
URL.revokeObjectURL(anchor.href)
anchor.remove()
}
var input = "this is a string to test"
createTextFile(input)
and if you wanted to save in server side with php there is function in php
file-put-contents

Sending data from javascript to php to generate a pdf but doesn't work

I am using JavaScript to take the info from a form completed by the user, then sending this data to PHP and generate a PDF with FPDF. The problem is I want the browser to ask the user to save the PDF or view it online but
I cannot figure out how. The PDF generates correctly but only when I save it directly to a certain path specified by me.
The question is how do you guys send data from JavaScript to PHP to generate a PDF file then the browser asks the user to open or download, Or how can I make a function where the user can retrieve this PDF.
The JavaScript:
function senddata() {//this activates when i push a button not a submit
var peticion = new XMLHttpRequest();
peticion.open('POST', 'generatepdf.php');
var nueva2 = {};
var key;
for (i = 0; i < 6; i++) {
key = document.forms[0].elements[i].id;
nueva2[key] = document.forms[0].elements[i].value;
}//here i take my data from the form and make an object
var json = JSON.stringify(nueva2);//here i tranform my object to json string so i can send it to my php
var parametros = "json_string=" + json;//here I do this so later I can easily transform the $_POST to an array in the form json_decode($_POST["json_string"],true);
peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
peticion.send(parametros);//it sends ok
}
The PHP with the FPDF class and things
<?php
require('fpdf/fpdf.php');
require('functions.php');
if($_SERVER['REQUEST_METHOD']=='POST'){
$datos=json_decode($_POST["json_string"],true); //here i have my data in an array format so i can use the parameters to fill my pdf fields
//...lots of pdf things here...//
$pdf->Output('F',"pdfs/Cotizacion ".$datos["nombres"]." ".$datos["apellidos"].".pdf");//this works but never ask the user
//$pdf->Output('D',"pdfs/Cotizacion ".$datos["nombres"]." ".$datos["apellidos"].".pdf");//this should force a dowload or send to the browser but doesnt work
//$pdf->Output();//this should send to the browser but doesnt work
}
To view your PDF inline to the browser, you should use the I variable instead. View full documentation here.
Also I don't think outputting the file in two methods at the same time works. It might conflict each other. The best way to do that is to test each method and if it does conflict each other just simply add a condition for the user to decide whether he/she wants to download or view it in the browser. Hope this helps.

How to upload and process CSV File using ExtJS Client Side

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

How to download a file via URL then get its name

This is for a userscript I'm making with JS+jQuery. I'm wondering if it's possible to find the filename given the URL.
It's in the form of:
http://example.org/download.php?action=download&id=1234
and then that link downloads a file such as "cat.jpg".
How do I find out what the file name is called? I don't need to actually save the file on the users computer - just need to find the name of the file.
I'm open to using any JS library - but I need to make sure that the file isn't actually saved in the users computer (or maybe it's just saved in a temp folder somewhere).
The simple thing you can do is to make HEAD request, so that you don't actually download the file but only response headers. From there you get Content-Disposition header which contains filename field.
Something like this in jQuery:
$.ajax({
type: "HEAD",
url: 'http://example.org/download.php?action=download&id=1234',
success: function(message, text, response) {
var header = response.getResponseHeader('Content-Disposition');
console.log(header);
}
});
header variable will be something like attachment; filename="image.jpg". Now it's easy to extract filename part:
var filename = header.match(/filename="(.+)"/)[1]; // image.jpg

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...

Categories

Resources