Ask your JavaScript questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Trying to read a file into a variable from input JavaScript


Trying to read a file into a variable. But it just creates alert(current html )

<input type="file" onclick = "mattress();" id="fileInput" />

function mattress(){
tuna = document.getElementById('fileInput').value;
.then(response => response.text())
.then((data) => {


Answers (2)


Rainner Lins answers:

Make sure to run the JS code after the html for the input.


mohitseth answers:

You can do following:

function mattress(event) {
let input =;
let reader = new FileReader();
reader.onload = function(){
const content = reader.result;
<input type="file" onchange="mattress(event);" id="fileInput" />

You can follow the FileReader API documentation for more details on FileReader with different files.

User180435 comments:

Where do I put an alert? Has to be simp[le text, not base64.

User180435 comments:

I want an alert with file contents displayed. (Not a useless div)

User180435 comments:

If an alert is not available, I'll accept placing the file contents into a variable.

User180435 comments:

Uncaught ReferenceError: content is not defined
at mattress (localhost/:2185)