Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue upload local json file

I can't find answer to my problem and I think it's possible in only Vue.js, but I'm not 100% sure. So problem is that. I want user to select file from his computer, it's always will be json file. It is possible to get that file and work with it with just Vue.js or I need some backend to this.

like image 766
Michał Kruk Avatar asked Oct 14 '25 12:10

Michał Kruk


1 Answers

There is nothing specific to Vue here, and there is no need for a server.

The way to do it is with the special <input type="file">, and a FileReader().

document.getElementById('import').onclick = () => {
  const files = document.getElementById('selectFiles').files;
  if (files.length <= 0) {
    return false;
  }

  const fr = new FileReader();

  fr.onload = e => {
    const result = JSON.parse(e.target.result);
    const formatted = JSON.stringify(result, null, 2);
    document.getElementById('result').innerHTML = formatted;
  }
  fr.readAsText(files.item(0));
};
<input type="file" id="selectFiles" value="Import" /><br />
<button id="import">Import The File!</button>
<pre id="result"></pre>

Obviously, this code can easily be implemented in a Vue app.

like image 88
Shaya Ulman Avatar answered Oct 17 '25 02:10

Shaya Ulman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!