I have a comma separated variable in my .js file, for example:
var out='';
out+="1,val1,val2,val3,val4\n";
out+="2,val1,val2,val3,val4\n";
out+="3,val1,val2,val3,val4\n";
I am displaying this value in a browser using document.write(out);.
I would like the out variable to be downloadable as a .csv file.
From data stored in a variable, is there any way to create a csv file and its associated download link in JavaScript?
jsFiddle
Depends on browser support, but that's getting pretty good with new browsers: http://jsfiddle.net/3fMeL/2/
var CSV = [
'"1","val1","val2","val3","val4"',
'"2","val1","val2","val3","val4"',
'"3","val1","val2","val3","val4"'
].join('\n');
window.URL = window.webkitURL || window.URL;
var contentType = 'text/csv';
var csvFile = new Blob([CSV], {type: contentType});
var a = document.createElement('a');
a.download = 'my.csv';
a.href = window.URL.createObjectURL(csvFile);
a.textContent = 'Download CSV';
a.dataset.downloadurl = [contentType, a.download, a.href].join(':');
document.body.appendChild(a);
So the first item is the Blob object, this creates the object that can be downloaded. https://developer.mozilla.org/en-US/docs/Web/API/Blob (http://caniuse.com/#search=blob)
The next part is the download attribute of the link, which informs the browser to download the CSV file rather than opening it in the browser window. (http://caniuse.com/#feat=download)
there is jquery plugin for output file at the client side without server side interaction,
https://github.com/dcneiner/Downloadify
Related
I use vue-signature Library and I Don't know how to download base64 data generated as image,
Here is Link of library : https://www.npmjs.com/package/vue-signature
I've already read the documentation and see That "Save()" Methods Save image as PNG/JPG… but it give me base64 data,
thank you for your collaboration, I use vue js
This is not the most optimized solution, But it works.
var a = document.createElement("a"); //Create <a>
a.href = "data:image/png;base64," + ImageBase64; //Image Base64 Goes here
a.download = "Image.png"; //File name Here
a.click(); //Downloaded file
In your case you can try this
var canvas = document.querySelector("canvas");
var signaturePad = new SignaturePad(canvas);
// Returns signature image as data URL (see https://mdn.io/todataurl for the list of possible parameters)
signaturePad.toDataURL("image/jpeg"); // save image as JPEG
source : https://vuejsexamples.com/vue-signature-pad-component/
I have the following code to create a file from Base64.
var byteCharacters =atob(content);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray]);
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
window.navigator.msSaveOrOpenBlob(blob, 'msSaveBlob_testFile.docx');
The problem is that when I execute the msSaveOrOpenBlob it ask the user for downloading/saving of file, what I want is to automatically save it to user c drive.
I think this can be done using ActiveX in IE but even when I used ActiveX to save docx file although it saved the file but it says file is corrupted, but for simple txt file it works fine.
var FileOpener = new ActiveXObject("Scripting.FileSystemObject");
var FilePointer = FileOpener.OpenTextFile("C:\taqi.docx", 2, true);
FilePointer.WriteLine("some text");
FilePointer.Close();
even writing simple string to docx file, give me error of invalid file. But if I open the same docx file in notepad than I can see the text.
Now my question is how can I use the blob object to create file silently. the file can be (txt,docx,ppt,pdf)
Any help will be appreciated.
Thanks
For security purpose browsers don't permit saving files on the user's computer without his permission.
Consider using localstorage to save it in the browser instead :
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
I am developing a WebRTC application that transfers file over WebRTC data channel. After I successfully transfer the file as data url, I want to create a link says "Click to download" from that data url.
I have used HTML 5 <a> tag with download attribute to create that content. An examplary content as follows;
<a download="fileName" href="data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,UEsDBBQABgAIAAA...sc1BLBQYAAAAAGQAZAKoGAAD9eQAAAAA=">
It worked just fine for small contents that lesser than 16MB or so, but for bigger contents, it just didn't worked and nothing happened when you click.
Then I tried to open new page with data url as follows;
// event.message.content is base 64 data url
window.open(event.message.content,'Downloading');
This solution also worked for small contents, but failed to download big contents.
How could I download big content by using Javascript(pure javascript if possible) and HTML 5? Is there any more efficent way than base64? Thanks to CBroe, now I know that base64 is not the efficent way. What would be the efficent way to do this?
Please feel free to ask for details if any missing.
Thanks,
Ugurcan
Edit: I've tried following code snippet, it worked for small content but not worked for bigger content too. It is probably same thing with the first one.
var save = document.createElement('a'),
event;
save.href = message.content;
save.target = '_blank';
save.download = message.identifier;
event = document.createEvent('Event');
event.initEvent('click', true, true);
save.dispatchEvent(event);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
Following code snippet derived from this answer helped me to get Blob from base64 data uri.
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {
type: mimeString
});
}
Then I wrote this code snippet in order to download Blob content
var blob = dataURItoBlob(message.content);
var blobUrl = URL.createObjectURL(blob);
var save = document.createElement('a'),
event;
save.href = blobUrl;
save.download = message.identifier;
event = document.createEvent('Event');
event.initEvent('click', true, true);
save.dispatchEvent(event);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
Thanks for your kind help folks.
my project is about recording audio using html5.I'm saving the audio in a blob.I want to use the data in that blob to convert it to mp3 or any other format using ffmpeg,my problem is that when calling the fileName of the audio, it's giving me an error that invalid data was found when calling input.In other words, its not reading the fileName of the audio I'm recording.
here is my code for saving the fileName and downloading it:
var blob = new Blob ( [ view ], { type : 'audio/wav' } );
// let's save it locally
// let's save it locally
document.getElementById('output').innerHTML = 'Handing off the file now...';
var url = (window.URL || window.webkitURL).createObjectURL(blob);
console.log(url);
var link = window.document.createElement('a');
link.href = url;
link.download = 'output.wav';
var fileName=link.download;
console.log(link.download);
my question is: why I can't retrieve the fileName of the audio file.although in the console its getting me back the name of the file, but when accessing that file it gives me no data to be found.what is going wrong??
Is there a way to generate an .xslx file from javascript and allow the user to download it by javascript? This page is geared towards being run offline in html 5 with no internet connectivity.
You could generate a data URI, and let the user save the link. However, IE8 has very limited support for data URIs. There is a 32 KB limit, and it's not allowed to be used with a href.
Also, you still need to find a actual XLSX JS library... But it is possible.
It has been done successfully by Ed Spencer. This project is using an EXT DataGrid as the source of the data, but I'm sure you could adapt it pretty easily.
**Yes You Can do it using javascript**
** call function expexcel('table_id','output_file_name');**
<script>
function expexcel(tableID, filename = ''){
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById(tableID);
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
filename = filename?filename+'.xls':'excel_data.xls';
// Create download link element
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', tableHTML], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, filename);
}else{
// Create a link to the file
downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
}
</script>
As Javascript has no file I/O, it's not going to be easy for your users to download. However, this kind of work is perfectly suited for a simple PHP script, which could generate your XSLX and save to your server dynamically.
You can generate any Office document with
OpenXML SDK for Javascript
http://openxmlsdkjs.codeplex.com/
As for allowing the user to save a file from JS I recommend FileSaver.js
https://github.com/eligrey/FileSaver.js/