In a Webbrowser, you can't just write to the clients machines disk for
security reasons.
However, there are several exceptions to that:
* A file can be downloaded. If an "a" tag has a link and the download
attribute set to the desired name, clicking it will download the linked
file. This can be authomated, and the URL can be an object url, created
in js with any data in it you want:
1 | function download(data, name, mime){
|
2 | mime = mime || 'application/octet-stream';
|
3 | let a = document.createElement("a");
|
4 | a.style.display = 'none';
|
5 | a.download = name || "file.dat";
|
6 | let blob = new Blob([data],{type:mime});
|
7 | let url = URL.createObjectURL(blob);
|
8 | a.href = url;
|
9 | document.body.appendChild(a);
|
10 | a.click();
|
11 | setTimeout(function(){
|
12 | a.parentElement.removeChild(a);
|
13 | }, 600);
|
14 | }
|
* The drag & drop API can be used to drag an element from the webpage
somewhere else, and it can be made such that it'll save a file if
dropped into a folder on the clients PC. To do this, an element needs
the draggable attribute, then a handler for the dragstart event needs to
be registered, and the data to be saved set using
event.dataTransfer.setData. You need to set at least DownloadURL, but I
recommend to also provide an entry for the files mime type and
text/uri-list. Example: https://gist.github.com/dgdsp/974987
* There is now also a very new File System Access API, that allows to
give a website access to a clients files by letting the user select
those files using a file picker dialog, or existing means such as drag &
drop, but support for this API isn't available on all browsers yet:
https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API
There are smilar caviats to reading files, it's generally not possible,
but there are various exceptions to this. Generally, local file system
access usually requires some form of user interaction, (except for
downloading a single file).
If you want to just store data locally to be used by the browser in the
future, there are variouse other & better ways to do that, for example:
localStorage/sessionStorage, Cookies, indexedDB, (and the FileSystem
API, not to be confused with the File System Access API, or the API
chrome provided before that, but I wouldn't recommend using those yet.)