Depending on the side the file is in, you could proceed in two ways: by reading the file from the client's device (explained in A), or from the server (explained in B).
A. IF THE FILE IS ON THE CLIENT'S SIDE
You can do it using FileReader . The client must select the file by clicking on the button:
function leerArchivo(e) {
var archivo = e.target.files[0];
if (!archivo) {
return;
}
var lector = new FileReader();
lector.onload = function(e) {
var contenido = e.target.result;
mostrarContenido(contenido);
};
lector.readAsText(archivo);
}
function mostrarContenido(contenido) {
var elemento = document.getElementById('contenido-archivo');
elemento.innerHTML = contenido;
}
document.getElementById('file-input')
.addEventListener('change', leerArchivo, false);
<input type="file" id="file-input" />
<h3>Contenido del archivo:</h3>
<pre id="contenido-archivo"></pre>
Note:
This method is compatible with:
- IE 10 +
- Firefox 3.6 +
- Chrome 13 +
- Safari 6.1 +
B. IF THE FILE IS ON THE SERVER'S SIDE
You can do it with jQuery. In the example, the url of the file is entered in the input and pressing the button requests the file from the server using the get method of Ajax If the answer is satisfactory, the file is displayed on a div.
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
$(function()
{
$("#button").click( function()
{
//var TXT_URL = 'https://www.mozilla.org/media/MPL/2.0/index.815ca599c9df.txt';
var TXT_URL = $("#input-url").val();
$.ajax
(
{
url : TXT_URL,
dataType: "text",
success : function (data)
{
$(".text").html("<pre>"+data+"</pre>");
}
}
);
});
});
</script>
Ingrese una url válida:<input type="text" id="input-url" size="50" value="https://www.mozilla.org/media/MPL/2.0/index.815ca599c9df.txt"></input>
<input type="button" id="button" value="Ver .txt"></input>
<div class="text">
<hr />
<h2>Texto:</h2>
</div>