Home > Net >  How to not make inputType-file send data to another php file?
How to not make inputType-file send data to another php file?

Time:11-26

I am trying to build a page that would just do three things:

  • Make the user choose a file (a .json file to be specific)
  • Simply Read the file's contents and store them in a variable. (do not store anywhere)
  • Process the contents' variable further using Javascript. (I'll be using JS to convert the file into XML. I have the conversion code ready & working, it just needs the json string, which would be fetched from the file contents' variable. After converting to XML, I'll export the XML file so the user would download it, and import it in my MS Excel Sheet, which has XML mappings to populate data. [I am yet to figure the export option])

So far I have acquired some code-snippets to use in some parts of my code:

To access the php variable (containing contents) in JS :

<?php
$somevar = 'Hi Thunkable!';
?>

<script>
var msg = <?php echo $somevar; ?>;
.... process the variable further
</script>

Input-type: file form for the upload button as I have the JS code in the current file, how do I make the form NOT send data to another php file?

<form enctype="multipart/form-data" action="__URL__" method="POST">
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>

The only part remains for me is as I said above, instead of sending the uploaded file data to another PHP file, store it in a variable. I found out that $txt = file_get_contents($_FILES['userfile']['tmp_name']); could get the contents from a file.

Summing up, I am just trying to keep all my code in one HTML file, which includes uploading the file, reading it's contents and storing in a var., and processing the contents further. Is something like this possible to do? I am a beginner in PHP/HTML/JS so I couldn't think of anything to search beforehand regarding my question...

CodePudding user response:

You can use object FileReader for read files from the input type file

here is the example:

(function(){
    
    function onChange(event) {
        var reader = new FileReader();
        reader.onload = (event)=>{
          alert(event.target.result);
          let data = JSON.parse(event.target.result);
          //process the data here
          console.log(data);
        }
        reader.readAsText(event.target.files[0]);
    }
 
    document.getElementById('file').addEventListener('change', onChange);

}());
<input id="file" type="file" accept="application/JSON" />
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related