I am trying to save an excel file that I get from a post as base64, this conversion is done in my view, once I convert it, I try to save it with the xlsx library, this file is saving fine but when opening the file, it does not contain nothing. Can someone help me, in knowing what I am doing wrong?
my following code is:
private async getCurp(req: Request, res: Response) {
var datos = [];
let arrayusers = {};
const {
curp
} = req.body;
const newCurp = new CurpModel({
curp
});
const path = "C:\\Miroute"
var bufferFile = Buffer.from(curp, "base64");
const data = XLSX.read(bufferFile, { type: 'buffer' })
XLSX.writeFile(data, "excel.xls");
try {
return Ok<CurpType>(res, newCurp);
}
catch (error) {
console.log(error);
return ServerError(res);
}
In my component I convert my excel file to base64 in this way, iam using react
handleFileChange = e => {
let idCardBase64 = '';
this.getBase64(e.target.files[0], (result) => {
idCardBase64 = result;
console.log(idCardBase64)
this.setState({
file: idCardBase64,
})
});
}
getBase64(file, cb) {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
cb(reader.result)
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
Please can someone help me?
My solution: I had not realized that my input parameter had a different name so it was undefined, the code looked like this:
private async getCurp(req: Request, res:Response){
var datos = [];
let arrayusers = {};
const {
file
} = req.body;
const newCurp = new CurpModel({
file
});
const bufferExcel = Buffer.from(newCurp.file.toString().replace("data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64", ""),'base64');
const workbook = XLSX.read(bufferExcel, { type: 'buffer' });
const sheetNamesList = workbook.SheetNames;
// parse excel data to json
const excelData = XLSX.utils.sheet_to_json(workbook.Sheets[sheetNamesList[0]]);
console.log(excelData);
try{
return Ok<CurpType>(res, newCurp);
}
catch(error){
console.log(error);
return ServerError(res);
}
}