Skip to content
Sign upLog in
← Back to Community

How to load a file from a `<input type="file">` and put it into the element `rixxyplayerCode`?

Profile icon
RixTheTyrunt

I tried a StackOverflow link that shows how to read uploaded files and put it into a element, but seems like the code didn't work ( Some of that code are NOT FROM THE ANSWER ) . How to do it?

Voters
Profile icon
-mintanimator-
Profile icon
MattDESTROYER
Profile icon
RixTheTyrunt
Comments
hotnewtop
Profile icon
MattDESTROYER

A working example

<script type="text/javascript"> function openFile(event, useDataUrl = false) { let reader = new FileReader(); reader.onload = function () { // this is the text or data url from the file reader.result; }; if (useDataUrl) { reader.readAsDataURL(event.target.files[0]); } else { reader.readAsText(event.target.files[0]); } } </script> <input type="file" onchange="openFile(event, false);" />
Profile icon
RixTheTyrunt

Woah, you use tabs!

Profile icon
RixTheTyrunt

No replacing 4 spaces with a tab anymoore!

Profile icon
RixTheTyrunt

Wait, NOT WORKING!!!

Profile icon
MattDESTROYER

@RixTheTyrunt
Make sure you open your project in a new tab, this deinitely works for text based files (.txt, .json, etc), if it's still not working let me know :)

Profile icon
MattDESTROYER

@RixTheTyrunt
If you've just copied and pasted the code block I posted that won't work, this is probably what you should do:

<div id="rixxyplayerCode" spellcheck="false" style="display: none;"></div> <script type="text/javascript"> function openFile(event, useDataUrl = false) { let reader = new FileReader(); reader.onload = function () { document.getElementById("rixxyplayerCode").textContent = reader.result; }; if (useDataUrl) { reader.readAsDataURL(event.target.files[0]); } else { reader.readAsText(event.target.files[0]); } } </script> <input type="file" onchange="openFile(event);" />
Profile icon
RixTheTyrunt

I already defined document.getElementById("rixxyplayerCode") in a variable named code ;D

Profile icon
RixTheTyrunt

But thank you very much!

Profile icon
RixTheTyrunt

This actually works...

Profile icon
MattDESTROYER

@RixTheTyrunt
No problem :)