我想导入CSV文件并在其上读取数据而不将文件保存在服务器中。 我该怎么办?
我更喜欢使用Dojo,但如果不可能,我可以使用HTML输入类型文件。
this.import = new Uploader({
label: "Import",
showLabel: true,
iconClass: "uploadBtn",
multiple: false,
uploadOnSelect: false,
onBegin: function() {
progressDialog.show();
},
onProgress: function(rev) {
console.log("progress", rev);
if (rev.type === "load") {
progressDialog.close();
this.reset();
// READ THE FILE AND USE THE DATA
}
},
onChange: function() {
console.log("file: ", this.getFileList());
var file = this.getFileList();
if (file[0].type != "text/csv"){
console.log("not a csv file");
this.reset();
}else{
this.upload(file[0]);
}
}
}, domConstruct.create("div", {
style: ""
}, this.toolbarNode));
this.import.startup();
答案 0 :(得分:0)
我解决了!
this.uploader = domConstruct.create("input", {
type: "file",
accept: ".csv",
change: function(e) {
// console.log(e);
var uploader = this;
if (e.target.files && e.target.files[0]) {
var FR = new FileReader();
FR.onload = function(up) {
var format = up.target.result.substring(up.target.result.indexOf("/") + 1, up.target.result.indexOf(";"));
if (format == "csv") {
var base64 = up.target.result.substring(up.target.result.indexOf(",") + 1, up.target.result.length);
var csv = window.atob(base64);
// Split the input into lines
var lines = csv.split('\n');
// Extract column names from the first line
var columnNamesLine = lines[0];
var columnNames = parse(columnNamesLine);
// Extract data from subsequent lines
var dataLines = lines.slice(1);
var data = dataLines.map(parse);
// Prints the array of the colomuns
// console.log(columnNames);
if (columnNames[0] == "Code" && columnNames[1] == "Description") {
// Prints the data
// console.log(data);
var dataObjects = data.map(function(arr) {
var dataObject = {};
columnNames.forEach(function(columnName, i) {
dataObject[columnName] = arr[i];
});
return dataObject;
});
// Prints the DATA object
console.log(dataObjects); // FINAL DATA
} else {
// NOTIFICATION: format error
}
} else {
// NOTIFICATION: file format error
}
uploader.value = "";
};
FR.readAsDataURL(e.target.files[0]);
}
}
});