Thanks to Nelson Yeung for uploading excel file and insert to MongoDB. Next, I'm trying to implement this solution on React with MongoDB and insert the document on the server side.
I'm done the code that look fine on client side but on the server side it cannot insert the document to the MongoDB. Could anybody help me please?
My code is here: On the client side ->
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Meteor } from 'meteor/meteor';
import { Tracker } from 'meteor/tracker';
import { Slingshot } from 'meteor/edgee:slingshot';
const XLSX = require('xlsx');
class Upload extends Component {
constructor(props) {
super(props);
this.state = {
isUploading: false,
};
this.handleUpload = this.handleUpload.bind(this);
}
handleUpload(event) {
this.upload = new Slingshot.Upload('Upload');
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = function(e) {
const data = e.target.result;
const name = file.name;
Meteor.call('upload', data, name, function(err, wb) {
if(err) console.error(err);
else {
document.getElementById('out').innerHTML = JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]),2,2);
}
});
};
reader.readAsBinaryString(file);
}
render() {
return (
<div className="Upload">
<div>
<input
onChange={ this.handleUpload }
type="file"
name="Upload"
/>
<p><i className="fa fa-cloud-upload" /> <span>Click or Drop Files to Upload</span></p>
</div>
<div id="out"></div>
</div>
);
}
}
Upload.propTypes = {};
export default Upload;
On the server side ->
import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { check } from 'meteor/check';
export const Registers = new Mongo.Collection('registers');
const XLSX = require('xlsx');
Meteor.methods({
'upload': function upload(data, name) {
const wb = XLSX.read(data, {type:'binary'});
return wb;
XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]).forEach(r => Registers.insert(r));
},
});
I just swap return and insertion then it's working so nice.