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

  • SOLVED

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


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

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

})
}
</script>

Answers (2)

2019-11-11

Rainner Lins answers:

https://jsfiddle.net/rainnerlins/xbkus263/

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

2019-11-11

mohitseth answers:

You can do following:

<script>
function mattress(event) {
let input = event.target;
let reader = new FileReader();
reader.onload = function(){
const content = reader.result;
};
reader.readAsDataURL(input.files[0]);
}
</script>
<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)