For the security concern, client-side JavaScript does not provide any way to read, write, create, delete, or list files or directories on the client/server computer. But one can use Ajax to read the file. This code snippet can be used to read from a text file.

Code Snippet

function get_XMLHttpRequest(){

    if (window.XMLHttpRequest) // For most of the browser that follows standard
	    return new XMLHttpRequest();
    else if (window.ActiveXObject) //  < 7IE
	    return new ActiveXObject("Microsoft.XMLHTTP");
    else
	    return null; // Browser does not support AJAX.
} 
 
function ReadAllText(file) {
	
	try
	{
		var objXmlHttp = get_XMLHttpRequest();

		if (objXmlHttp != null) {
			objXmlHttp.open("GET", file, true);
			objXmlHttp.send(null);
			objXmlHttp.onreadystatechange = function () {
				if (objXmlHttp.readyState == 4 && objXmlHttp.status === 200){
					
					//do something here what you want to do with content of the file.
					alert(objXmlHttp.responseText);
				}
			}
		}
		else {alert('Oops! Sorry, your browser does not support AJAX.');}
	}
	catch(e){
		alert(e.message);
	}
}

Sample Usage

<a href="javascript:ReadAllText('file-location');">Read All Text</a>

Note

Sample file location for remote site >> http://www.domain.com/sample.txt
Sample file location for local file >> file:///c:/sample.txt


Categories : Programming
Tags : ajax, File


author's photo

Author : Blue Cloud

Just a normal software developer who love to write code. Developing professional software since 1999. After working in the software industry for many years, I've started my own website to share knowledges and experiences.

COMMENTS
blog comments powered by Disqus