Read and save files
The FileReader object allows to asynchronously read the contents of files using File or Blob objects.
The File interface doesn't define any methods, but inherits methods from the Blob interface. You can use File anywhere you can use Blob.
read file
The <input> element with type="file" allows the user to choose one or more files from their device storage. Read more details about file chooser.
Choose .txt file.<br>
<input type="file" id="userFile"
accept=".txt">
<br>
<textarea id="txtContent" rows="10">
</textarea>
<script>
function onFileSelect(e){
var file = e.target.files[0];
var fr = new FileReader();
fr.onload = function (frEvent){
document.getElementById("txtContent")
.value = frEvent.target.result;
}
fr.readAsText(file);
}
document.getElementById("userFile")
.onchange=onFileSelect;
</script>
Choose .txt file.
save file
function download(file, filename) {
if (window.navigator.msSaveOrOpenBlob) // IE10+
window.navigator.msSaveOrOpenBlob(file, filename);
else {
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);
}
}
download(new Blob([ "Hello world!"], {
type: 'text/plain'
}), "hello.txt");
There is FileSaver.js that resolves saving files on the client-side. It is perfect for web apps that generates files on the client.
FileReader
name | description |
---|---|
properties | |
result | The file's contents. This property is only valid after the read operation is complete, and the format of the data depends on which of the methods was used to initiate the read operation. |
readyState | Current state of reader, can be one of following:
|
onload | A handler for the load event. This event is triggered each time the reading operation is successfully completed. |
onerror | A handler for the error event. |
methods | |
abort() | Aborts the read operation. Upon return, the readyState will be DONE. |
readAsArrayBuffer(bf) | Reads the content of the specified Blob or File and stores the result as an ArrayBuffer. |
readAsDataURL(file) | Reads the content of the specified Blob or File and stores the result as a data: URL representing the file's data. |
readAsText(file, enc) | Reads the content of the specified Blob or File and stores the result as a text string. |