I am trying to download a CSV file from json data stored in a variable.
The issue is that I am not able to set the name of the downloaded file.
Here is the code...
$('#downloadCSV').click(function () {
var exportData = 'data:attachment/csv;charset=utf-8,';
exportData += 'nodeid,value\n1,212\n';
var newWindow = window.open(encodeURI(exportData));
return false;
});
I have already tried to add the HTML5 download attr:
<a id="downloadCSV" download="data.csv" href="#">Download CSV</a>
I have already tried the solutions provided by others and nothing is working with the current browsers ...
I find the FileSaver library a really useful cross-browser solution for saving files from JavaScript. Their documentation provides a compatibility table which will show you which browsers support file names.
BTW the download attribute on the <a> tag is an HTML5 feature which would apply if you were linking to a file's URL directly with the href. As you are catching the click event using JavaScript, and then returning false, this will not be doing anything.
Related
I am trying to build a mini browser using Electron.js. Is it possible to make urls like chrome://settings or about:config, so that when the user goes to that link I can show an html file? I basically want to associate a url with a file in electron.
You could use Data URIs, and base64-encode the contents of your data as a link. You can use Javascript to encode and decode binary data, then you just specify the MIME type at the start.
If you go to the following URL in a browser for example you'll see a png decoded and rendered:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
The MDN Web doc in the first link mentions the process of base64 encoding an HTML file.
Alternatively, if you just want to force the download of a link you could add the download attribute to your anchor.
You can use did-start-navigation to detect when they go to chrome://settings/ then intercept that and tell it to go to https://stackoverflow.com/ instead.
Here's the code:
mainWin.webContents.on('did-start-navigation', function (evt, navigateUrl) {
if (navigateUrl == 'chrome://settings/') {
evt.preventDefault();
setTimeout(function () { // Without this it just crashes, no idea why.
mainWin.loadURL('https://stackoverflow.com/');
}, 0);
}
});
I tried the `will-navigate` event, but it didn't work.
Docs for: did-start-navigation
After a little searching at npm, I found a package that does exactly what I want, it's electron protocols. It's a simple way to add custom protolcs in Electron, Here's an example"
const protocols = require('electron-protocols');
const path = require('path');
protocols.register('browser', uri => {
let base = app.getAppPath();
if(uri.hostname == "newtab"){
return path.join(base,"newtab.html")
}
});
In this example, if you go to the link browser://newtab, it opens newtab.html. And if you type location.href the DevTools it shows browser://newtab there too
After browsing around the internet for a few hours to find a solution, I found out a few methods of getting the information from a filereader, but not quite to what I need.
function submitfile() {
var reader = new FileReader();
reader.readAsDataURL(document.getElementById("filesubmission").files[0]);
reader.onload = function (REvent) {
document.getElementById("outputcontent").innerHTML = "<iframe width='100%' id='outputdata' scrolling='yes' onload='resizeIframe(this)' src='"+REvent.target.result+"'></iframe>";
};
}
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
That is the code that I'm using after a user selects a file, which I allow .html, .htm, .txt, or .xml. The Iframe is then resized to match the content. I have that functionality working, however I need to have a method of replacing text in the iframe with certain values that the user provides in <input> tags earlier. An example would be I need to be able to replace "[c1]" in the file the user provides with a client's name, such as "John Smith".
The way I would prefer to do this would be through the content of the file itself, rather than using a source in an iframe or data in an object. If I can get this into the original file itself where it can be edited, that would solve the problem.
I need to be able to do this without the use of jQuery or other plugins, since this is a local file that should be able to work standalone as a tool for my client.
Use the DOMParser to parse the reader's result:
var doc = (new DOMParser).parseFromString(reader.result,"text/html");
or any other mime type,
Then, update the some nodes within the doc based on the inputs you mention.
Then use the iframe's contentDocument to adopt the node using document.adoptNode. That will return the node with its ownerDocument pointing to the iframe. Lastly append it to the iframe's body.
I have a simple javascript application that lets the user generate some XML and then save it as a file. However I can't get the saving to work in IE.
Currently I am using the data-uri method as exemplified in this jsfiddle. But this does not work in IE because it does not support data-uri for application/xml. What would be another method or workaround (client-only) to let the user easily save an xml string (or dom node) as a file?
The correct answer was given by Mr Anonymous in the comment.
$("a").click(function(e){
var xml = $("textarea").text();
if(window.navigator && window.navigator.msSaveBlob){
e.preventDefault();
navigator.msSaveBlob( new Blob([xml], {type:'application/xml'}), "myfile.xml" )
} else {
$(this).attr("href", "data:application/xml," + encodeURIComponent(xml));
}
});
I want to do what Downloadify does in this other question: How do I dynamically create a document for download in Javascript?
But I would like to do it without using Flash. How can that be done?
I think the best you can do is something like this:
function addDownloadLinkTo(elem, base64data) {
var link = document.createElement('a');
var text = document.createTextNode('Download');
link.appendChild(text);
link.setAttribute('href', 'data:application/octet-stream;base64,' + base64data);
elem.appendChild(link);
}
Or if you're using jQuery,
$(elem).append($('Download');
where base64data can be obtained as in this question.
Unfortunately, data URIs do not yet (AFAIK) provide a mechanism to specify the file name; also, might not work in all browsers.
I have a feeling security concerns may not allow this but is it possible to generate a file with JavaScript and allow the user to drag it to the desktop (or file system)?
The following code drags out a file from a server
files[0].addEventListener("dragstart",function(evt){
evt.dataTransfer.setData("DownloadURL", "application/octet-stream:Eadui2.ttf:http://thecssninja.come/demo/gmail_dragout/Eadui.ttf");
},false);
And with the below code I can generate a file and have it download but I can't set the file name or let the user select the location.
var uriContent = "data:application/octet-stream," + encodeURIComponent(JSON.stringify(map));
location.href = uriContent;
Ideally I'd like a magical combination of both.
following code is currently working in Chrome only:
// generate downloadable URL, file name here will not affect stored file
var url = URL.createObjectURL(new File([JSON.stringify(map)], 'file_name.txt'));
// note that any draggable element may be used instead of files[0]
// since JSON.stringify returns a string, we use 'text' type in setData
files[0].addEventListener("dragstart", function(evt) {
evt.dataTransfer.setData("DownloadURL", "text:file_name.txt:" + url);
}, false);
now, dragging our files[0] element from the browser to desktop or file system, will store there a text file called, file_name.txt.
Feel free to choose another file name :)
This is only possible for Chrome, and even in Chrome you can't set the location. If using only Chrome is okay then you will have the following options:
Stick with Drag n' Drop like from the CSS Ninja's tutorial, then you should try Ben's answer. encodeURIComponent is one way, but if you have the file generated using BlobBuilder then you can use window.webkitURL.createObjectURL() to get the file's URL. You can also try using FileWriter() with requestFileSystem(TEMPORARY, ...).
Chrome supports download attribute for anchor tags so you can have regular link for the user to click (dragging also works):
Download
For cross browser support I suggest Downloadify.
You could try sending it to the server, saving the file, checking the return value and firing the download file function, followed by a server file that deletes the file from the server.
Something like this (with jQuery)
$.ajax({
url: 'saveFile.php',
method: 'post',
data: {
Filedata: data// file data variable
},
success: function(d) {
// save file function, where d is the filename
}
})
PHP:
$filename = ;//generate filename
file_put_contents($filename, $_POST['Filedata']);
echo $filename;
Obviously there is more to it but that should be the basics