Create and save a file with JavaScript

JavascriptFileDialogSave

Javascript Problem Overview


I have data that I want to write to a file, and open a file dialog for the user to choose where to save the file. It would be great if it worked in all browsers, but it has to work in Chrome. I want to do this all client-side.

Basically I want to know what to put in this function:

saveFile: function(data)
{
}

Where the function takes in data, has the user select a location to save the file, and creates a file in that location with that data.

Using HTML is fine too, if that helps.

Javascript Solutions


Solution 1 - Javascript

A very minor improvement of the code by Awesomeness01 (no need for anchor tag) with addition as suggested by trueimage (support for IE):

// Function to download data to a file
function download(data, filename, type) {
	var file = new Blob([data], {type: type});
	if (window.navigator.msSaveOrOpenBlob) // IE10+
		window.navigator.msSaveOrOpenBlob(file, filename);
	else { // Others
		var a = document.createElement("a"),
                url = URL.createObjectURL(file);
		a.href = url;
		a.download = filename;
		document.body.appendChild(a);
		a.click();
		setTimeout(function() {
			document.body.removeChild(a);
			window.URL.revokeObjectURL(url);  
		}, 0); 
	}
}

Tested to be working properly in Chrome, FireFox and IE10.

In Safari, the data gets opened in a new tab and one would have to manually save this file.

Solution 2 - Javascript

function download(text, name, type) {
  var a = document.getElementById("a");
  var file = new Blob([text], {type: type});
  a.href = URL.createObjectURL(file);
  a.download = name;
}

<a href="" id="a">click here to download your file</a>
<button onclick="download('file text', 'myfilename.txt', 'text/plain')">Create file</button>

And you would then download the file by putting the download attribute on the anchor tag.

The reason I like this better than creating a data url is that you don't have to make a big long url, you can just generate a temporary url.

Solution 3 - Javascript

This project on github looks promising:

https://github.com/eligrey/FileSaver.js

> FileSaver.js implements the W3C saveAs() FileSaver interface in > browsers that do not natively support it.

Also have a look at the demo here:

http://eligrey.com/demos/FileSaver.js/

Solution 4 - Javascript

Choosing the location to save the file before creating it is not possible. But it is possible, at least in Chrome, to generate files using just JavaScript. Here is an old example of mine of creating a CSV file. The user will be prompted to download it. This, unfortunately, does not work well in other browsers, especially IE.

<!DOCTYPE html>
<html>
<head>
	<title>JS CSV</title>
</head>
<body>
	<button id="b">export to CSV</button>
	<script type="text/javascript">
		function exportToCsv() {
			var myCsv = "Col1,Col2,Col3\nval1,val2,val3";

			window.open('data:text/csv;charset=utf-8,' + escape(myCsv));
		}

		var button = document.getElementById('b');
		button.addEventListener('click', exportToCsv);
	</script>
</body>
</html>

Solution 5 - Javascript

function download(text, name, type) {
  var a = document.getElementById("a");
  var file = new Blob([text], {type: type});
  a.href = URL.createObjectURL(file);
  a.download = name;
}

<a href="" id="a">click here to download your file</a>
<button onclick="download('file text', 'myfilename.json', 'text/json')">Create file</button>

I think this can work with json files too if you change the mime type.

Solution 6 - Javascript

For latest browser, like Chrome, you can use the File API as in this tutorial:

window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTENT, 5*1024*1024 /*5MB*/, saveFile, errorHandler);

Solution 7 - Javascript

Tried this in the console, and it works.

var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // the blob
window.open(URL.createObjectURL(oMyBlob));

Solution 8 - Javascript

function SaveBlobAs(blob, file_name) {
    if (typeof navigator.msSaveBlob == "function")
        return navigator.msSaveBlob(blob, file_name);

    var saver = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
    var blobURL = saver.href = URL.createObjectURL(blob), 
        body = document.body;

    saver.download = file_name;

    body.appendChild(saver);
    saver.dispatchEvent(new MouseEvent("click"));
    body.removeChild(saver);
    URL.revokeObjectURL(blobURL);
}

Solution 9 - Javascript

You cannot do this purely in Javascript. Javascript running on browsers does not have enough permission yet (there have been proposals) due to security reasons.

Instead, I would recommend using Downloadify:

> A tiny javascript + Flash library that enables the creation and download of text files without server interaction.

You can see a simple demo here where you supply the content and can test out saving/cancelling/error handling functionality.

Solution 10 - Javascript

For Chrome and Firefox, I have been using a purely JavaScript method.

(My application cannot make use of a package such as Blob.js because it is served from a special engine: a DSP with a WWWeb server crammed in and little room for anything at all.)

function FileSave(sourceText, fileIdentity) {
    var workElement = document.createElement("a");
    if ('download' in workElement) {
        workElement.href = "data:" + 'text/plain' + "charset=utf-8," + escape(sourceText);
        workElement.setAttribute("download", fileIdentity);
        document.body.appendChild(workElement);
        var eventMouse = document.createEvent("MouseEvents");
        eventMouse.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        workElement.dispatchEvent(eventMouse);
        document.body.removeChild(workElement);
    } else throw 'File saving not supported for this browser';
}

Notes, caveats, and weasel-words:

  • I have had success with this code in both Chrome and Firefox clients running in Linux (Maipo) and Windows (7 and 10) environments.
  • However, if sourceText is larger than a MB, Chrome sometimes (only sometimes) gets stuck in its own download without any failure indication; Firefox, so far, has not exhibited this behavior. The cause might be some blob limitation in Chrome. Frankly, I just don't know; if anybody has any ideas how to correct (or at least detect), please post. If the download anomaly occurs, when the Chrome browser is closed, it generates a diagnostic such as Chrome browser diagnostic
  • This code is not compatible with Edge or Internet Explorer; I have not tried Opera or Safari.

Solution 11 - Javascript

StreamSaver is an alternative to save very large files without having to keep all data in the memory.
In fact it emulates everything the server dose when saving a file but all client side with service worker.

You can either get the writer and manually write Uint8Array's to it or pipe a binary readableStream to the writable stream

There is a few example showcasing:

  • How to save multiple files as a zip
  • piping a readableStream from eg Response or blob.stream() to StreamSaver
  • manually writing to the writable stream as you type something
  • or recoding a video/audio

Here is an example in it's simplest form:

const fileStream = streamSaver.createWriteStream('filename.txt')

new Response('StreamSaver is awesome').body
  .pipeTo(fileStream)
  .then(success, error)

If you want to save a blob you would just convert that to a readableStream

new Response(blob).body.pipeTo(...) // response hack
blob.stream().pipeTo(...) // feature reference

Solution 12 - Javascript

Javascript has a FileSystem API. If you can deal with having the feature only work in Chrome, a good starting point would be: http://www.html5rocks.com/en/tutorials/file/filesystem/.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1756980View Question on Stackoverflow
Solution 1 - JavascriptKanchuView Answer on Stackoverflow
Solution 2 - JavascriptAwesomeness01View Answer on Stackoverflow
Solution 3 - JavascriptlostsourceView Answer on Stackoverflow
Solution 4 - JavascriptMatt GreerView Answer on Stackoverflow
Solution 5 - JavascriptNoel OttView Answer on Stackoverflow
Solution 6 - JavascriptpdjotaView Answer on Stackoverflow
Solution 7 - JavascriptNetsi1964View Answer on Stackoverflow
Solution 8 - Javascriptuser12066722View Answer on Stackoverflow
Solution 9 - JavascriptAamirView Answer on Stackoverflow
Solution 10 - JavascriptWe B MartiansView Answer on Stackoverflow
Solution 11 - JavascriptEndlessView Answer on Stackoverflow
Solution 12 - JavascriptAlokView Answer on Stackoverflow