[英]Drag & Drop Json into Chrome
我正在寻找一种方法将json文件拖放到chrome中并提取它的信息。
You can use a combination of HTML5 Drag & Drop and FileReader
API to read the file: 您可以结合使用HTML5 Drag&Drop和
FileReader
API来读取文件:
var dnd = new DnDFileController('body', function(files) {
var f = files[0];
if (!f.type.match('application/json')) {
alert('Not a JSON file!');
}
var reader = new FileReader();
reader.onloadend = function(e) {
var result = JSON.parse(this.result);
console.log(result);
};
reader.readAsText(f);
});
DnDFileController
is from http://html5-demos.appspot.com/static/filesystem/filer.js/demos/js/dnd.js and just sets up the correct DnD event listeners on the element you pass in as the selector. DnDFileController
来自http://html5-demos.appspot.com/static/filesystem/filer.js/demos/js/dnd.js ,只是在您作为选择器传入的元素上设置正确的DnD事件侦听器。
See http://jsbin.com/oqosav/2/edit 见http://jsbin.com/oqosav/2/edit
Here's minimal working code that is self-contained, without external dependencies: 这是自包含的最小工作代码,没有外部依赖:
function dropJSON(targetEl, callback) {
// disable default drag & drop functionality
targetEl.addEventListener('dragenter', function(e){ e.preventDefault(); });
targetEl.addEventListener('dragover', function(e){ e.preventDefault(); });
targetEl.addEventListener('drop', function(event) {
var reader = new FileReader();
reader.onloadend = function() {
var data = JSON.parse(this.result);
callback(data);
};
reader.readAsText(event.dataTransfer.files[0]);
event.preventDefault();
});
}
dropJSON(
document.getElementById("dropTarget"),
function(data) {
// dropped - do something with data
console.log(data);
}
);
The code doesn't contain any sanity checks or error handling. 该代码不包含任何健全性检查或错误处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.