How to Read a File in Js
How to read a local text file using JavaScript?
HTML 5 provides a standard way to interact with local files with the help of File API. The File API allows interaction with unmarried, multiple as well as Hulk files. The FileReader API can be used to read a file asynchronously in collaboration with JavaScript event handling. However, all the browsers do not accept HTML 5 support so information technology is important to test the browser compatibility before using the File API. There are four inbuilt methods in the FileReader API to read local files:
- FileReader.readAsArrayBuffer(): Reads the contents of the specified input file. The result attribute contains an ArrayBuffer representing the file's data.
- FileReader.readAsBinaryString(): Reads the contents of the specified input file. The result attribute contains the raw binary information from the file as a string.
- FileReader.readAsDataURL(): Reads the contents of the specified input file. The result aspect contains a URL representing the file's data.
- FileReader.readAsText(): Reads the contents of the specified input file. The result aspect contains the contents of the file as a text cord. This method tin take encoding version equally the second argument(if required). The default encoding is UTF-eight.
In this case we are using FileReader.readAsText() method to read local .txt file.
<!DOCTYPE html>
<html>
<head>
<championship>Read Text File</championship>
</head>
<body>
<input blazon=
"file"
proper name=
"inputfile"
id=
"inputfile"
>
<br>
<pre id=
"output"
></pre>
<script type=
"text/javascript"
>
document.getElementById(
'inputfile'
)
.addEventListener(
'change'
,
function
() {
var
fr=
new
FileReader();
fr.onload=
function
(){
document.getElementById(
'output'
)
.textContent=fr.result;
}
fr.readAsText(
this
.files[0]);
})
</script>
</trunk>
</html>
This lawmaking prints the content of the input file exactly the same as is there in the input file.
JavaScript is best known for web page development but information technology is also used in a variety of non-browser environments. You can learn JavaScript from the footing up by following this JavaScript Tutorial and JavaScript Examples.
Source: https://www.geeksforgeeks.org/how-to-read-a-local-text-file-using-javascript/
0 Response to "How to Read a File in Js"
Post a Comment