Download A File At Different Location Using HTML5 - javascript

I am downloading files using HTML5 from below codes that you can see live in action at JSBIN HTML5 Download File DEMO and its working perfectly file and downloading my files at my browser default Download Folder.
<!DOCTYPE html>
<html>
</head>
</head>
<body>
<table>
<tr><td>Text To Save:</td></tr>
<tr>
<td colspan="3">
<textarea id="inputTextToSave" style="width:512px;height:256px"></textarea>
</td>
</tr>
<tr>
<td>Filename To Save As:</td>
<td><input id="inputFileNameToSaveAs"></td>
<td><button onclick="saveTextAsFile()"> Save Text To File </button></td>
</tr>
<tr>
<td>Select A File To Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>
</table>
<script type='text/javascript'>
function saveTextAsFile()
{
var textToWrite = document.getElementById("inputTextToSave").value;
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null)
{
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
else
{
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
function loadFileAsText()
{
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
</script>
</body>
</html>
But I want to download it on different location. Like I am using this code offline and just have the upper code in my index.html file. When I run this file in my browser from file:///C:/Users/Public/Desktop/ then it download the file and save it at file:///C:/Users/Public/Downloads/. So I want to download this file from where its called. For this I am picking the path from the following code. and its giving me the path as /C:/Users/Public/Desktop/ so I want to save file here. Whereever my this index.html file will go, it will download the file and save it along index.html file. How is this possible?
var url = window.location.pathname;
var folderpath = url.substring(0,url.lastIndexOf('/')+1);
alert(folderpath);

It's not possible because this poses a security risk. People use fairly real information for their folder structure and accessing the folder names in itself poses an immediate risk. As described here:
Get browser download path with javascript
Most OSs tend to just default to a Download location and this is something the user decides through the Browser they use. Not the website.
In Chrome, Download location setting can be found at chrome://settings/downloads

This is now possible in most Chromium based desktop browsers (and safari soon), using the File System Access API. https://caniuse.com/native-filesystem-api
An example on how to do this can be found here: https://web.dev/file-system-access/#create-a-new-file
Something along the lines of:
async function getHandle() {
// set some options, like the suggested file name and the file type.
const options = {
suggestedName: 'HelloWorld.txt',
types: [
{
description: 'Text Files',
accept: {
'text/plain': ['.txt'],
},
},
],
};
// prompt the user for the location to save the file.
const handle = await window.showSaveFilePicker(options);
return handle
}
async function save(handle, text) {
// creates a writable, used to write data to the file.
const writable = await handle.createWritable();
// write a string to the writable.
await writable.write(text);
// close the writable and save all changes to disk. this will prompt the user for write permission to the file, if it's the first time.
await writable.close();
}
// calls the function to let the user pick a location.
const handle = getHandle();
// save data to this location as many times as you want. first time will ask the user for permission
save(handle, "hello");
save(handle, "Lorem ipsum...");
This will prompt the user with a save file picker where he can choose a location to save the file to. In the options, you can specify a suggested name and the file type of the file to be saved.
This will return a file handle, which can be used to write data to the file. Once you do this, the user is asked for write permission to the created file. If granted, your app can save data to the file as many times as you like, without re-prompting the user, until all tabs of your app are closed.
The next time your app is opened, the user is prompted for permission again, if you use the same file handle again (the handles can be saved in IndexedDB to persist them across page loads).
The File System Access API also allows you to let the user pick an existing file, for your app to save later. https://web.dev/file-system-access/#ask-the-user-to-pick-a-file-to-read

Related

How to save data with pwa

I am working on my own project where I want to create an application, which runs on android and iOS. I decide using HTML, CSS and JavaScript for creating a PWA. The app should enable the user to manage recips for tart incl. Cost calculation. My problem is, that I want to save the recips/ingredients in form of a table. The data should be stored permanently locally on the device. With the method "localstorage" the data are only saved temporarily. I don't want to host a webserver/database. The data should not be lost when the user delete the local cache of the browser.
Is it possible to store general data with java script, for example in a text file, outside of the browser's cache?
In your case indexedDB would be my go to solution. It can be deleted by a user as all data stored in the browser. Browser can't store data in text files (at least as per October 2021)
It is possible. but it's not straightforward it must be done manually by the user.
You can generate your DB as a downloadable file -eg. .txt or .csv- and provide the download link for the user or just auto-download it.
here's an example.
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
// Start file download.
document.getElementById("dwn-btn").addEventListener("click", function(){
// Start the download of yournewfile.txt file with the content from the text area
var text = document.getElementById("text-val").value;
var filename = "yournewfile.txt";
download(filename, text);
}, false);
to load the data you can create an import button that receives the data and populates the table.
here's how you can read file data
function readImage(file) {
// Check if the file is text.
if (file.type && !file.type.startsWith('text/')) {
console.log('File is not an textfile.', file.type, file);
return;
}
const reader = new FileReader();
reader.addEventListener('load', (event) => {
img.src = event.target.result;
});
reader.readAsDataURL(file);
}
I recommend using this approach with indexedDb or local storage.

Connecting HTML/DOM with node.js

I'm trying to find a way to write to a text file using node.js but I was trying to get the input from the HTML DOM. How do you write the output from the DOM to a text file using fs.writeFile?
Here's some code that doesn't work but thought it might be relevant. Thanks
<h3>A demonstration of how to access a Text Field</h3>
<input id="myText">
<button onclick="myFunction()">Try it</button>
<script>
const fs = require('fs')
function myFunction() {
var content = document.getElementById("myText").value;
}
fs.writeFile('./test.txt', content, err => {
if(err){
console.log(err);
return
}
})
</script>
You cannot write file directly from a browser to local computers.
That would be a massive security concern.
*You also cannot use fs on client-side browser
Instead you get inputs from a browser, and send it to your server (NodeJs), and use fs.writeFile() on server-side, which is allowed.
What you could do is:
Create a link and prompt to download.
Send to server and response with a download.
Use native environment like Electron to able NodeJs locally to write into local computer.
What I assume you want to do is 1
Is that case you could simply do:
function writeAndDownload(str, filename){
let yourContent = str
//Convert your string into ObjectURL
let bom = new Uint8Array([0xef, 0xbb, 0xbf]);
let blob = new Blob([bom, yourContent], { type: "text/plain" });
let url = (window.URL || window.webkitURL).createObjectURL(blob);
//Create a link and assign the ObjectURL
let link = document.createElement("a");
link.style.display = "none";
link.setAttribute("href", url);
link.setAttribute("download", filename);
//Automatically prompt to download
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
writeAndDownload("Text you want to save", "savedData")

Html/JavaScript: Overwrite file every time it downloads

Is it possible to overwrite a file each time it saves. I have a textarea in html and i'm using JavaScript to save the text to a file. It is currently saving as: test.txt, test(1).txt, test(2).txt. Is it possible to get it to save a test.txt every time it's downloaded.
The code i'm using to download is the following:
function saveTextAsFile()
{
var textToWrite = document.getElementById("inputTextToSave").value;
var textFileAsBlob = new Blob([textToWrite], {type:'plan/text'});
var fileNameToSaveAs = "test.txt";
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "My Hidden Link";
window.URL = window.URL || window.webkitURL;
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
Thanks for your help.
No , a javascript script doesn't have access to the filesystem and therefore cant manipulate files, all it can do is suggest to the browser that a stream wants to be downloaded and also suggest a name for that stream. The browser is responsible for deciding what and how will be downloaded (you can add plugins and extensions to the browsers to enforce this particular behavior, but i do not think that this was what you needed)
EDIT:
On second note you could actually do that with a java applet. However i cannot help you with that, and in all sincerity, you should not (for one it wont work on chrome, also unless you have a really important reason to, it would be like killing a mosquito with a nuclear bomb, not to mention the chance of accidentally deleting a file from the user's side and a storm of alerts that would make your application look suspicious as it wont have any real reason to use java from they eyes of the user)

Import to notepad using jquery

Is there any link for exporting the datas to notepad?
I have some fields like
Name,
Age, and
WorkingStatus
These are text and textarea...
I want to insert this datas to the notepad.Is there any demos or code available?
I don't know of any way to have the browser open notepad, but you can use HTML5 features to save a file as text, and then open it on your own inside notepad. Depending on the browser, you may need to trigger saving the file on the user side. Here's two references, which I'll summarize:
http://thiscouldbebetter.wordpress.com/2012/12/18/loading-editing-and-saving-a-text-file-in-html5-using-javascrip/
http://updates.html5rocks.com/2011/08/Saving-generated-files-on-the-client-side
Basically, you want to create and save a blob with your text. It should look something like this:
var arrayOfStuff = [];
arrayOfStuff.push("Name Age Working status");
arrayOfStuff.push("-----------------------------------------------");
arrayOfStuff.push(document.getElementById("name").value);
// etc
var blob = new Blob(arrayOfStuff, {type:'text/plain'});
// (the rest is copied directly from the wordpress link)
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null)
{
// Chrome allows the link to be clicked programmatically.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
downloadLink.click();
}
else
{
// Firefox requires the user to actually click the link.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
document.body.appendChild(downloadLink);
}
If notepad isn't a big deal, you should also be able to open this blob in an iframe as .txt, and then right-click and saveAs, if you prefer.
Edit
Ok, this was actually new for me to play with, so some of my older information wasn't quite right. Here's the javascript from the working fiddle:
var arrayOfStuff = [];
arrayOfStuff.push(document.getElementById("name").value + "\n");
arrayOfStuff.push(document.getElementById("email").value);
arrayOfStuff.push("\n");
arrayOfStuff.push(document.getElementById("phone").value);
arrayOfStuff.push("\n");
arrayOfStuff.push(document.getElementById("comments").value);
arrayOfStuff.push("\n");
alert(arrayOfStuff);
var blob = new Blob(arrayOfStuff, {type:'text/plain'});
var link = document.getElementById("downloadLink");
link.download = "details.txt";
link.href = window.URL.createObjectURL(blob);
The fiddle is at http://jsfiddle.net/xHH46/2/
There are a few lessons learned:
If you're on firefox, it gives you the option to open the .txt immediately in Notepad. However, notepad isn't paying attention to the linefeeds, whether they're \n or \n\r, appended to the immediate string or added separately, so I'd recommend using Wordpad instead. Or, you can save the file.
More importantly, realize that the link you display is based on whatever value is in the text when you create the blob. If you don't have defaults, you'll get an empty file, because all the fields are empty. The wordpress solution fixes this (and discusses using it within the past week), but the fix is ugly. Basically, you'd have to click on a button, and the button would then make a link appear, and that link would give you the good file.
You won't be able to do this with purely javascript. You need to generate the file server side and send it to the client.

Using HTML5/JavaScript to generate and save a file

I've been fiddling with WebGL lately, and have gotten a Collada reader working. Problem is it's pretty slow (Collada is a very verbose format), so I'm going to start converting files to a easier to use format (probably JSON). I already have the code to parse the file in JavaScript, so I may as well use it as my exporter too! The problem is saving.
Now, I know that I can parse the file, send the result to the server, and have the browser request the file back from the server as a download. But in reality the server has nothing to do with this particular process, so why get it involved? I already have the contents of the desired file in memory. Is there any way that I could present the user with a download using pure JavaScript? (I doubt it, but might as well ask...)
And to be clear: I am not trying to access the filesystem without the users knowledge! The user will provide a file (probably via drag and drop), the script will transform the file in memory, and the user will be prompted to download the result. All of which should be "safe" activities as far as the browser is concerned.
[EDIT]: I didn't mention it upfront, so the posters who answered "Flash" are valid enough, but part of what I'm doing is an attempt to highlight what can be done with pure HTML5... so Flash is right out in my case. (Though it's a perfectly valid answer for anyone doing a "real" web app.) That being the case it looks like I'm out of luck unless I want to involve the server. Thanks anyway!
Simple solution for HTML5 ready browsers...
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
if (document.createEvent) {
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
pom.dispatchEvent(event);
}
else {
pom.click();
}
}
Usage
download('test.txt', 'Hello world!');
OK, creating a data:URI definitely does the trick for me, thanks to Matthew and Dennkster pointing that option out! Here is basically how I do it:
1) get all the content into a string called "content" (e.g. by creating it there initially or by reading innerHTML of the tag of an already built page).
2) Build the data URI:
uriContent = "data:application/octet-stream," + encodeURIComponent(content);
There will be length limitations depending on browser type etc., but e.g. Firefox 3.6.12 works until at least 256k. Encoding in Base64 instead using encodeURIComponent might make things more efficient, but for me that was ok.
3) open a new window and "redirect" it to this URI prompts for a download location of my JavaScript generated page:
newWindow = window.open(uriContent, 'neuesDokument');
That's it.
HTML5 defined a window.saveAs(blob, filename) method. It isn't supported by any browser right now. But there is a compatibility library called FileSaver.js that adds this function to most modern browsers (including Internet Explorer 10+). Internet Explorer 10 supports a navigator.msSaveBlob(blob, filename) method (MSDN), which is used in FileSaver.js for Internet Explorer support.
I wrote a blog posting with more details about this problem.
Saving large files
Long data URIs can give performance problems in browsers. Another option to save client-side generated files, is to put their contents in a Blob (or File) object and create a download link using URL.createObjectURL(blob). This returns an URL that can be used to retrieve the contents of the blob. The blob is stored inside the browser until either URL.revokeObjectURL() is called on the URL or the document that created it is closed. Most web browsers have support for object URLs, Opera Mini is the only one that does not support them.
Forcing a download
If the data is text or an image, the browser can open the file, instead of saving it to disk. To cause the file to be downloaded upon clicking the link, you can use the the download attribute. However, not all web browsers have support for the download attribute. Another option is to use application/octet-stream as the file's mime-type, but this causes the file to be presented as a binary blob which is especially user-unfriendly if you don't or can't specify a filename. See also 'Force to open "Save As..." popup open at text link click for pdf in HTML'.
Specifying a filename
If the blob is created with the File constructor, you can also set a filename, but only a few web browsers (including Chrome & Firefox) have support for the File constructor. The filename can also be specified as the argument to the download attribute, but this is subject to a ton of security considerations. Internet Explorer 10 and 11 provides its own method, msSaveBlob, to specify a filename.
Example code
var file;
var data = [];
data.push("This is a test\n");
data.push("Of creating a file\n");
data.push("In a browser\n");
var properties = {type: 'text/plain'}; // Specify the file's mime-type.
try {
// Specify the filename using the File constructor, but ...
file = new File(data, "file.txt", properties);
} catch (e) {
// ... fall back to the Blob constructor if that isn't supported.
file = new Blob(data, properties);
}
var url = URL.createObjectURL(file);
document.getElementById('link').href = url;
<a id="link" target="_blank" download="file.txt">Download</a>
function download(content, filename, contentType)
{
if(!contentType) contentType = 'application/octet-stream';
var a = document.createElement('a');
var blob = new Blob([content], {'type':contentType});
a.href = window.URL.createObjectURL(blob);
a.download = filename;
a.click();
}
Take a look at Doug Neiner's Downloadify which is a Flash based JavaScript interface to do this.
Downloadify is a tiny JavaScript + Flash library that enables the generation and saving of files on the fly, in the browser, without server interaction.
Simple Solution!
<a download="My-FileName.txt" href="data:application/octet-stream,HELLO-WORLDDDDDDDD">Click here</a>
Works in all Modern browsers.
I've used FileSaver (https://github.com/eligrey/FileSaver.js) and it works just fine.
For example, I did this function to export logs displayed on a page.
You have to pass an array for the instanciation of the Blob, so I just maybe didn't write this the right way, but it works for me.
Just in case, be careful with the replace: this is the syntax to make this global, otherwise it will only replace the first one he meets.
exportLogs : function(){
var array = new Array();
var str = $('#logs').html();
array[0] = str.replace(/<br>/g, '\n\t');
var blob = new Blob(array, {type: "text/plain;charset=utf-8"});
saveAs(blob, "example.log");
}
You can generate a data URI. However, there are browser-specific limitations.
I found two simple approaches that work for me. First, using an already clicked a element and injecting the download data. And second, generating an a element with the download data, executing a.click() and removing it again. But the second approach works only if invoked by a user click action as well. (Some) Browser block click() from other contexts like on loading or triggered after a timeout (setTimeout).
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function linkDownload(a, filename, content) {
contentType = 'data:application/octet-stream,';
uriContent = contentType + encodeURIComponent(content);
a.setAttribute('href', uriContent);
a.setAttribute('download', filename);
}
function download(filename, content) {
var a = document.createElement('a');
linkDownload(a, filename, content);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
</script>
</head>
<body>
download
<button onclick="download('test.txt', 'Hello World!');">download</button>
</body>
</html>
try
let a = document.createElement('a');
a.href = "data:application/octet-stream,"+encodeURIComponent('"My DATA"');
a.download = 'myFile.json';
a.click(); // we not add 'a' to DOM so no need to remove
If you want to download binary data look here
Update
2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop works (due to sandbox security restrictions) - but JSFiddle version works - here
Here is a link to the data URI method Mathew suggested, it worked on safari, but not well because I couldn't set the filetype, it gets saved as "unknown" and then i have to go there again later and change it in order to view the file...
http://www.nihilogic.dk/labs/canvas2image/
You can use localStorage. This is the Html5 equivalent of cookies. It appears to work on Chrome and Firefox BUT on Firefox, I needed to upload it to a server. That is, testing directly on my home computer didn't work.
I'm working up HTML5 examples. Go to http://faculty.purchase.edu/jeanine.meyer/html5/html5explain.html
and scroll to the maze one. The information to re-build the maze is stored using localStorage.
I came to this article looking for HTML5 JavaScript for loading and working with xml files. Is it the same as older html and JavaScript????
As previously mentioned the File API, along with the FileWriter and FileSystem APIs can be used to store files on a client's machine from the context of a browser tab/window.
However, there are several things pertaining to latter two APIs which you should be aware of:
Implementations of the APIs currently exist only in Chromium-based browsers (Chrome & Opera)
Both of the APIs were taken off of the W3C standards track on April 24, 2014, and as of now are proprietary
Removal of the (now proprietary) APIs from implementing browsers in the future is a possibility
A sandbox (a location on disk outside of which files can produce no effect) is used to store the files created with the APIs
A virtual file system (a directory structure which does not necessarily exist on disk in the same form that it does when accessed from within the browser) is used represent the files created with the APIs
Here are simple examples of how the APIs are used, directly and indirectly, in tandem to do this:
BakedGoods*
bakedGoods.get({
data: ["testFile"],
storageTypes: ["fileSystem"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(resultDataObj, byStorageTypeErrorObj){}
});
Using the raw File, FileWriter, and FileSystem APIs
function onQuotaRequestSuccess(grantedQuota)
{
function saveFile(directoryEntry)
{
function createFileWriter(fileEntry)
{
function write(fileWriter)
{
var dataBlob = new Blob(["Hello world!"], {type: "text/plain"});
fileWriter.write(dataBlob);
}
fileEntry.createWriter(write);
}
directoryEntry.getFile(
"testFile",
{create: true, exclusive: true},
createFileWriter
);
}
requestFileSystem(Window.PERSISTENT, grantedQuota, saveFile);
}
var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);
Though the FileSystem and FileWriter APIs are no longer on the standards track, their use can be justified in some cases, in my opinion, because:
Renewed interest from the un-implementing browser vendors may place them right back on it
Market penetration of implementing (Chromium-based) browsers is high
Google (the main contributer to Chromium) has not given and end-of-life date to the APIs
Whether "some cases" encompasses your own, however, is for you to decide.
*BakedGoods is maintained by none other than this guy right here :)
This thread was invaluable to figure out how to generate a binary file and prompt to download the named file, all in client code without a server.
First step for me was generating the binary blob from data that I was saving. There's plenty of samples for doing this for a single binary type, in my case I have a binary format with multiple types which you can pass as an array to create the blob.
saveAnimation: function() {
var device = this.Device;
var maxRow = ChromaAnimation.getMaxRow(device);
var maxColumn = ChromaAnimation.getMaxColumn(device);
var frames = this.Frames;
var frameCount = frames.length;
var writeArrays = [];
var writeArray = new Uint32Array(1);
var version = 1;
writeArray[0] = version;
writeArrays.push(writeArray.buffer);
//console.log('version:', version);
var writeArray = new Uint8Array(1);
var deviceType = this.DeviceType;
writeArray[0] = deviceType;
writeArrays.push(writeArray.buffer);
//console.log('deviceType:', deviceType);
var writeArray = new Uint8Array(1);
writeArray[0] = device;
writeArrays.push(writeArray.buffer);
//console.log('device:', device);
var writeArray = new Uint32Array(1);
writeArray[0] = frameCount;
writeArrays.push(writeArray.buffer);
//console.log('frameCount:', frameCount);
for (var index = 0; index < frameCount; ++index) {
var frame = frames[index];
var writeArray = new Float32Array(1);
var duration = frame.Duration;
if (duration < 0.033) {
duration = 0.033;
}
writeArray[0] = duration;
writeArrays.push(writeArray.buffer);
//console.log('Frame', index, 'duration', duration);
var writeArray = new Uint32Array(maxRow * maxColumn);
for (var i = 0; i < maxRow; ++i) {
for (var j = 0; j < maxColumn; ++j) {
var color = frame.Colors[i][j];
writeArray[i * maxColumn + j] = color;
}
}
writeArrays.push(writeArray.buffer);
}
var blob = new Blob(writeArrays, {type: 'application/octet-stream'});
return blob;
}
The next step is to get the browser to prompt the user to download this blob with a predefined name.
All I needed was a named link I added in the HTML5 that I could reuse to rename the initial filename. I kept it hidden since the link doesn't need display.
<a id="lnkDownload" style="display: none" download="client.chroma" href="" target="_blank"></a>
The last step is to prompt the user to download the file.
var data = animation.saveAnimation();
var uriContent = URL.createObjectURL(data);
var lnkDownload = document.getElementById('lnkDownload');
lnkDownload.download = 'theDefaultFileName.extension';
lnkDownload.href = uriContent;
lnkDownload.click();
When testing the "ahref" method, I found that the web developer tools of Firefox and Chrome gets confused. I needed to restart the debugging after the a.click() was issued. Same happened with the FileSaver (it uses the same ahref method to actually make the saving). To work around it, I created new temporary window, added the element a into that and clicked it there.
function download_json(dt) {
var csv = ' var data = ';
csv += JSON.stringify(dt, null, 3);
var uricontent = 'data:application/octet-stream,' + encodeURI(csv);
var newwin = window.open( "", "_blank" );
var elem = newwin.document.createElement('a');
elem.download = "database.js";
elem.href = uricontent;
elem.click();
setTimeout(function(){ newwin.close(); }, 3000);
}
You can use this to save text and other data:
function downloadFile(name, data) {
let a = document.createElement("a");
if (typeof a.download !== "undefined") a.download = name;
a.href = URL.createObjectURL(new Blob([data], {
type: "application/octet-stream"
}));
a.dispatchEvent(new MouseEvent("click"));
}
This function will create an Anchor element, set the name via .download (if supported), assign a url (.href) created from an object (URL.createObjectURL), in this case a Blob object, and dispatch a click event. In short: it's as if you're clicking a download link.
Example code
downloadFile("textfile.txt", "A simple text file");
downloadFile(
"circle.svg",
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="42" />
</svg>`
);
downloadFile(
"utf8string.txt",
new Uint8Array([85, 84, 70, 45, 56, 32, 115, 116, 114, 105, 110, 103]) // "UTF-8 string"
);
This function also accepts File, Blob and MediaSource:
function downloadFile(name, data) {
if (!(data instanceof File || data instanceof Blob || data instanceof MediaSource)) {
return downloadFile(name, new Blob([data], {
type: "application/octet-stream"
}));
}
let a = document.createElement("a");
if (typeof a.download !== "undefined") a.download = name;
a.href = URL.createObjectURL(data);
a.dispatchEvent(new MouseEvent("click"));
}
Or you could use two functions:
function downloadFile(name, data) {
return downloadObject(new Blob([data], {
type: "application/octet-stream"
}));
}
function downloadObject(name, object) {
let a = document.createElement("a");
if (typeof a.download !== "undefined") a.download = name;
a.href = URL.createObjectURL(object);
a.dispatchEvent(new MouseEvent("click"));
}
Here is a tutorial to export files as ZIP:
Before getting started, there is a library to save files, the name of library is fileSaver.js, You can find this library here. Let's get started, Now, include the required libraries:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.4/jszip.min.js" type="text/javascript"></script>
<script type="text/javascript" src="https://fastcdn.org/FileSaver.js/1.1.20151003/FileSaver.js" ></script>
Now copy this code and this code will download a zip file with a file hello.txt having content Hello World. If everything thing works fine, this will download a file.
<script type="text/javascript">
var zip = new JSZip();
zip.file("Hello.txt", "Hello World\n");
zip.generateAsync({type:"blob"})
.then(function(content) {
// see FileSaver.js
saveAs(content, "file.zip");
});
</script>
This will download a file called file.zip. You can read more here: http://www.wapgee.com/story/248/guide-to-create-zip-files-using-javascript-by-using-jszip-library
For simple files like 'txt' or'js' you can use the package fs-browsers.
It has nice and easy download and export methods for client-side which do not invole any server.
import { exportFile } from 'fs-browsers';
const onExportClick = (textToExport) => {
// Export to txt file
exportFile(textToExport);
}
If you want to change the name of the file, or even it's type you can do it easily with this:
import { exportFile } from 'fs-browsers';
const onExportClick = (textToExport) => {
// Export to js file called 'file.js'
exportFile(textToExport, { fileName: 'file.js' });
}
For more complex files you will need to involve a server as you said.
The package can also does that with excel files ('xls') if that is what you need.
import { exportFile, EXCEL_FILE } from 'fs-browsers';
const data = [{ "id": 5, "name": "John", "grade": 90, "age": 15 }, { "id": 7, "name": "Nick", "grade": 70, "age": 17 }];
const headings = ["Student ID", "Student Name", "Test Grade", "Student Age"];
exportFile(data, { type: EXCEL_FILE, headings: headings, fileName: 'grades.xls' });
Maybe in the future there eill be other kind of files too.

Categories