How can I upload a JSON file on some click on a button on my web page say "import", and use it to store in a variable to use and update it using JavaScript.
I have gone through the other posts but could not find any answer.
I am saving the JSON variable using this function:
function save(filename, data){ if(!data) { alert('error : No data') return; } if(typeof data === "object"){ data = JSON.stringify(data, undefined, 4) } var blob = new Blob([data], {type: 'text/json'}), e = document.createEvent('MouseEvents'), a = document.createElement('a') a.download = filename a.href = window.URL.createObjectURL(blob) a.dataset.downloadurl = ['text/json', a.download, a.href].join(':') e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null) a.dispatchEvent(e) }
This is working fine and it downloads the file on clicking another button say "export". How upload this file back and make a JSON variable of this file data?
While you cannot send a JSON file with HTTPUpload, you can send the JSON string with the API SetHTTPFormField. Dynamic Web TWAIN sends an HTTP POST request to the server when doing an upload. The SetHTTPFormField() method is used to add extra fields to the HTTP form.
One standard method we can use to read a JSON file (either a local file or one uploaded to a server) is with the Fetch API. It uses the same syntax for both. The only difference would be the URL. To fix this, we will make sure our JSON file is on a local or remote server.
Without server side code, your best approach may be to provide a textarea
element for the user to copy/paste the JSON into, and then parse it using JSON.parse
.
You could even go as far as to use something like Ace Editor to provide syntax highlighting for JSON - you can see it in action on the Ace Editor Kitchen Sink Demo - select JSON from the dropdown list in the top left.
Turns out I was wrong. Here is a fiddle demonstrating the FileReader in use, which is exactly what you need:
https://jsfiddle.net/Ln37kqc0/
Here is the code:
Javascript:
document.getElementById('import').onclick = function() { var files = document.getElementById('selectFiles').files; console.log(files); if (files.length <= 0) { return false; } var fr = new FileReader(); fr.onload = function(e) { console.log(e); var result = JSON.parse(e.target.result); var formatted = JSON.stringify(result, null, 2); document.getElementById('result').value = formatted; } fr.readAsText(files.item(0)); };
HTML:
<input type="file" id="selectFiles" value="Import" /><br /> <button id="import">Import</button> <textarea id="result"></textarea>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With