How can user upload an array (json file) at runtime?

Hi everyone

I want the user to upload a json file at runtime and read the content of that file and use it in the game.
I’m not very good with java and right now I have this code but it doesn’t do what I want

    const fileInput = document.createElement("input");
    fileInput.type = 'file';
    fileInput.accept = 'list.json';
    fileInput.style.position = 'absolute';
    document.body.appendChild(fileInput);


    fileInput.onchange = (e) => {
        const file = e.target.files[0];
        if (!file) return;
         
        const reader = new FileReader();

        reader.onload = (er) => {
            const list = document.createElement("list");

            var jsonContent = JSON.stringify(data);


               console.log(jsonContent);
    

        };

        reader.readAsDataURL(file);
  
    };

Hi @Majid_Ahmady,

How are you running this code in PlayCanvas? Are you putting it in a regular script? What error are you getting?

Hi Leonidas

here is a link to the project
https://playcanvas.com/editor/scene/1868280

when you push the button an ‘choose file’ appears on top right corner. I want to choose a JSON file and after that it show the content of that json (a simple array of names and numbers) file in the text element in the scene.

Good, update your method to this and it will work, you will get an object created by the JSON file:

    fileInput.onchange = (e) => {
        const file = e.target.files[0];
        if (!file) return;

        const reader = new FileReader();

        reader.onload = (er) => {
            const jsonContent = JSON.parse(reader.result);
            console.log(jsonContent);
        };

        reader.readAsText(file);
    };

Thank you Leonidas It works perfectly. :pray: :pray: :people_hugging:

one more thing right now when player pushes the button in the scene it creates a ‘choose file’ element and then player should push that to open a window to choose the file. is there a way to choose the file just by the button in the scene without the second button??

You could try and trigger the input element programmatically, after you have it in place and all of your previous code is ready to execute:

fileInput.dispatchEvent(new Event("input"));

Thanks again it was very helpful

1 Like