Javascript 上传 JSON 文件并使用它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36127648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uploading a JSON file and using it
提问by Abhishek Tripathi
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.
如何通过单击我网页上的“导入”按钮上传 JSON 文件,并使用它存储在变量中以使用 JavaScript 来使用和更新它。
I have gone through the other posts but could not find any answer.
我已经浏览了其他帖子,但找不到任何答案。
I am saving the JSON variable using this function:
我正在使用此函数保存 JSON 变量:
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?
这工作正常,它在单击另一个按钮时下载文件,说“导出”。如何上传此文件并制作此文件数据的 JSON 变量?
回答by Maloric
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
.
如果没有服务器端代码,您最好的方法可能是提供一个textarea
元素供用户将 JSON 复制/粘贴到其中,然后使用JSON.parse
.
You could even go as far as to use something like Ace Editorto 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.
您甚至可以使用Ace Editor 之类的工具为 JSON 提供语法高亮显示 - 您可以在Ace Editor Kitchen Sink Demo 中看到它的实际效果- 从左上角的下拉列表中选择 JSON。
Edit:
编辑:
Turns out I was wrong. Here is a fiddle demonstrating the FileReader in use, which is exactly what you need:
原来我错了。这是一个演示正在使用的 FileReader 的小提琴,这正是您所需要的:
https://jsfiddle.net/Ln37kqc0/
https://jsfiddle.net/Ln37kqc0/
Here is the code:
这是代码:
Javascript:
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:
HTML:
<input type="file" id="selectFiles" value="Import" /><br />
<button id="import">Import</button>
<textarea id="result"></textarea>
回答by Abhishek Tripathi
I have got a way to use the uploaded json file, here is the way i found.
我有一种方法可以使用上传的 json 文件,这是我找到的方法。
$("#inputFile").change(function(e) {
onChange(e);
});
function onChange(event) {
var reader = new FileReader();
reader.onload = onReaderLoad;
reader.readAsText(event.target.files[0]);
}
function onReaderLoad(event){
//alert(event.target.result);
var obj = JSON.parse(event.target.result);
alert(obj);
}
回答by khizer
Basic upload File:
基本上传文件:
<input id="contentFile" type="file" accept="application/json" />
document.getElementById('contentFile').onchange = function(evt) { try { let files = evt.target.files; if (!files.length) { alert('No file selected!'); return; } let file = files[0]; let reader = new FileReader(); const self = this; reader.onload = (event) => { console.log('FILE CONTENT', event.target.result); }; reader.readAsText(file); } catch (err) { console.error(err); } }
document.getElementById('contentFile').onchange = function(evt) { try { let files = evt.target.files; if (!files.length) { alert('No file selected!'); return; } let file = files[0]; let reader = new FileReader(); const self = this; reader.onload = (event) => { console.log('FILE CONTENT', event.target.result); }; reader.readAsText(file); } catch (err) { console.error(err); } }
`