Create file to download js - javascript

I'm receiving a JSON output from an API, and i want to use it with JS and also save that output to file. Is there any way to trigger the browser download machanism using JS with thet output?

Maybe now some browsers support the attribute download but you don't trigger the browser to automatically download the file.
the only way i know is #BAS's solution but without a filename.
tested in chrome ..
array=[{a:'1',b:'2'},{x:'3',y:'4'}];
function dl(array,filename){
var b=document.createElement('a');
b.download=filename;
b.textContent=filename;
b.href='data:application/json;base64,'+
window.btoa(unescape(encodeURIComponent(JSON.stringify(array))))
// or
// b.href='data:application/javascript;charset=utf-8,'+JSON.stringify(json);
return b
}
document.body.appendChild(dl(array,'my.json'));
example
http://jsfiddle.net/8yQcW/
UPDATE direct download works ... on chrome i tested.
on append simulate click
var e=document.createEvent('Events');
e.initEvent('click',true,false);
document.getElementById('dl').dispatchEvent(e);
http://jsfiddle.net/8yQcW/1/

You could try it with a data URI:
function triggerDownload(json) {
var dataUri = 'data:text;charset=utf-8,' + json;
window.open(dataUri);
}
Try entering data:text;charset=utf-8,{"Key":"Value"} into your browsers address bar. It should show you the save dialog.
See here for more information and browser support.

Related

Unable to download large data using javascript

I have a large data in form of JSON object in the javascript. I have converted it into the string using JSON.stringify(). Now my use case is to provide this large string in a text file to the user. So for this i have written below code.
HTML code
<button id='text_feed' type="submit">Generate ION Feed</button>
Javascript code
var text = //huge string
$("#text_feed").click(function() {
_generateFeed(text);
});
var _generateFeed = function(text) {
//some code here
$("#textLink").attr("href",
"data:attachment/txt," + encodeURIComponent(text)) [0].click();
});
};
Problem: When the string length is small , i am able to download the data .
But when the string length goes higher (> 10^5) , my page crashes.
This occurred because "encodeUriComponet(text)" is not able to encode large
data.
I also tried window.open("data:attachment/txt," + encodeURIComponent(text));
But again my page got crashed because of the same reason that encodeURIComponet was unable to encode such a large string.
Another approach: I was also thinking of writing the data into a file using HTML5 File write API , but it has support only in Chrome web browser , but i need to make this work for atleast firefox and chrome both.
Use Case
I don't want to do multiple downloads by breaking the data, as i need to have data in a single file in the end.
And my target is to support string of aprroximately 10^6 length. Can anyone help me how to download/write this amount of data into a single file.
From the OP:
I solved it as below.
var _generateFeed = function(text) {
/*some code here*/
var url = URL.createObjectURL( new Blob( [text], {type:'text/plain'} ) );
$("#textLink").attr("href",url)[0].click();
};
Notes:
URL.createObjectURL() is compatible with modern browsers and IE10+, but it is an unstable, experimental technology.
Objects created using URL.createObjectURL() "must be released by calling URL.revokeObjectURL() when you no longer need them." - MDN

node-webkit using window.open() to download a file open another window

I'm currently porting a nodejs / angular webapp to Windows using nodewebkit. Everything has been working pretty well for now but I'm facing a litle problem when I want the user to download a file.
In order to start the download with the save file Dialog, I use a simple window.open(url) where url can be a link to any kind of files. This line actually do it's job and pop the window dialog for saving a file, but at the same time, a blank node-webkit page appears.
I've been trying to mess around with node-webkit for a while without managing to remove this blank page.
As anyone experienced the same kind of behavior ?
I'll be interested in any lead, I'm not into the js stuff for long so I may have missed something obviouvs.
Have a nice wathever time of the day it is where you live !
a more better solution is found here
Step 1 In your html file, add a Input tag block like below:
<input id="export_file" type="file" nwsaveas style="display:none" nwworkingdir=""/>
Step 2 Add a new function in your javascript file like below:
function saveFile(name,data) {
var chooser = document.querySelector(name);
chooser.addEventListener("change", function(evt) {
console.log(this.value); // get your file name
var fs = require('fs');// save it now
fs.writeFile(this.value, data, function(err) {
if(err) {
alert("error"+err);
}
});
}, false);
chooser.click();
}
Step 3 Save your file where ever you like by using saveFile(name,data) function like below:
...
_exportCSV="you data to save";
saveFile('#export_file',_exportCSV);
...
As questioner said to be working:
location.href = url
Is the correct usage.

Auto Save a file in Firefox

I am trying to find a way where by we can auto save a file in Firefox using JS. The way I have done till yet using FireShot on a Windows Desktop:
var element = content.document.createElement("FireShotDataElement");
element.setAttribute("Entire", EntirePage);
element.setAttribute("Action", Action);
element.setAttribute("Key", Key);
element.setAttribute("BASE64Content", "");
element.setAttribute("Data", Data);
element.setAttribute("Document", content.document);
if (typeof(CapturedFrameId) != "undefined")
element.setAttribute("CapturedFrameId", CapturedFrameId);
content.document.documentElement.appendChild(element);
var evt = content.document.createEvent("Events");
evt.initEvent("capturePageEvt", true, false);
element.dispatchEvent(evt);
But the issue is that it opens a dialog box to confirm the local drive location details. Is there a way I can hard code the local drive storage location and auto save the file?
If you are creating a Firefox add-on then FileUtils and NetUtil.asyncCopy are your friends:
Components.utils.import("resource://gre/modules/FileUtils.jsm");
Components.utils.import("resource://gre/modules/NetUtil.jsm");
var TEST_DATA = "this is a test string";
var source = Components.classes["#mozilla.org/io/string-input-stream;1"].
createInstance(Components.interfaces.nsIStringInputStream);
source.setData(TEST_DATA, TEST_DATA.length);
var file = new FileUtils.File("c:\\foo\\bar.txt");
var sink = file.openSafeFileOutputStream(file, FileUtils.MODE_WRONLY |
FileUtils.MODE_CREATE);
NetUtil.asyncCopy(source, sink);
This will asynchronously write the string this is a test string into the file c:\foo\bar.txt. Note that NetUtil.asyncCopy closes both streams automatically, you don't need to do it. However, you might want to pass a function as third parameter to this method - it will be called when the write operation is finished.
See also: Code snippets, writing to a file
Every computer has a different file structure. But still, there is a way. You can save it to cookie / session, depends on how "permanent" your data wants to be.
Do not consider writing a physical file as it requires extra permission.

Fake file upload in Chrome not showing file name

I'm trying to use the solution over at quirksmode.org to sort the file upload input inconsistency problem, using the following javascript:
$('.sidebar-uploadcv input[type=file]').attr('onchange','javascript:document.getElementById("fakeupload").value = this.value').addClass('file_input_hidden');
The trouble is, this doesn't work properly in Chrome. It renders and the user can click to choose a file, but the filename isn't then displayed in the #fakeupload input.
Can anyone help?
Found the solution by invoking .change() instead of .attr('onchange',...). This method works cross-browser.
To get rid of the fakepath string in Webkit et al I've also added the var filename... line to strip out that part of the file name.
$('.input[type=file]').change( function() {
var filename = $(this).val().replace(/C:\\fakepath\\/i, '');
$('#fakeupload').val( filename );
});

How do I prompt user to save text (xml) to a file?

I've have some javascript code that transforms XML with XSLT. I now want the user to be able to save that new XML (either by prompting them or throwing the new XML up as a file or something so that the user can then save it. Anybody know how to do that?
var xmldoc = new ActiveXObject("Microsoft.XMLDOM");
xmldoc.async = false;
xmldoc.loadXML(responseText); // responseText is xml returned from ajax call
//apply the xslt
var xsldoc = new ActiveXObject("Microsoft.XMLDOM");
xsldoc.async = false;
xsldoc.load("../xslt/ExtraWorkRequest.xslt");
var content = xmldoc.transformNode(xsldoc);
How do I get the user to save the XML (content) as a file?
By default, you can't. Browser isn't supposed to access your local disks for security reasons.
But, if you can ask your user to change it's security settings (and you should not to ask), you can to use FileSystemObject or even your Microsoft.XMLDOM.Save method.
You cannot do it with 100% client-side JavaScript with the default security settings. You'll need to implement some server-side logic. In your case, you'll be able to do the XML transformation server-side, as well.
http://www.bigresource.com/Tracker/Track-javascripts-ijfTJlI9/
http://support.microsoft.com/kb/q260519/
You could construct a data: URI with a media type of application/octet-stream.
function download (data, charset) {
if (!charset) {
charset = document.characterSet;
}
location.href = ["data:application/octet-stream;charset=",
charset, ",", encodeURIComponent(data)
].join("");
}
All browsers except IE support data: URIs. I think IE8 may support them, but only for images. For IE, a workaround could be to send the data to a server (including document.characterSet) and then load a page that has something like the following header:
Content-Type: application/xml; charset={document.characterSet}
Content-Disposition: attachment
If you want to give the file a name too, use Content-Disposition: attachment; filename=....
Also, for any of this to work, you have to convert your XML to a string first.
I do this with code snippets on my blog (user can click on the save button, and the snippet will come up in their default text editor, where they can tweak it and/or copy it into their app).
It works by putting all the textual data inside of a hidden field, and then submits it to a very simple server-side HTTP handler. The handler just grabs the hidden field value and spits it right back out in the response with the right content-disposition header, giving the user the open/save download prompt.
This is the only way I could get it to work.

Categories

Resources