How to open a local file with JavaScript?
Question
The browser does not allow opening a local file using window.open('local_file.txt')
and $.ajax('local_file.txt')
, because of security reasons. However, I want to use the file's data in the client side. How can I read local file in JavaScript?
Solution - Use HTML5 FileReader
The HTML5 FileReader facility does allow you to process local files, but these MUST be selected by the user, you cannot go rooting about the users disk looking for files.
Here is an example using FileReader:
function readSingleFile(e) {
var file = e.target.files[0];
if (!file) {
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
// Display file content
displayContents(contents);
};
reader.readAsText(file);
}
function displayContents(contents) {
var element = document.getElementById('file-content');
element.innerHTML = contents;
}
document.getElementById('file-input').addEventListener('change', readSingleFile, false);
<input type="file" id="file-input" >
<div id="file-content"></div>
Solution - Use XMLHttpRequest
JavaScript cannot typically access local files in new browsers, but the XMLHttpRequest
object can be used to read files. So it is actually Ajax (and not Javascript) which is reading the file.
Here is an example to read file abc.txt:
var txt = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
txt = xmlhttp.responseText;
}
};
xmlhttp.open("GET","abc.txt",true);
xmlhttp.send();
References & Resources
- https://developer.mozilla.org/en-US/docs/Web/API/FileReader
- https://w3c.github.io/FileAPI/
Latest Post
- Dependency injection
- Directives and Pipes
- Data binding
- HTTP Get vs. Post
- Node.js is everywhere
- MongoDB root user
- Combine JavaScript and CSS
- Inline Small JavaScript and CSS
- Minify JavaScript and CSS
- Defer Parsing of JavaScript
- Prefer Async Script Loading
- Components, Bootstrap and DOM
- What is HEAD in git?
- Show the changes in Git.
- What is AngularJS 2?
- Confidence Interval for a Population Mean
- Accuracy vs. Precision
- Sampling Distribution
- Working with the Normal Distribution
- Standardized score - Z score
- Percentile
- Evaluating the Normal Distribution
- What is Nodejs? Advantages and disadvantage?
- How do I debug Nodejs applications?
- Sync directory search using fs.readdirSync