寻找适用于我的快速而精确的解决方案:
server.js
let express = require('express'),
app = express(),
bodyParser = require('body-parser'),
multer = require('multer'),
crypto = require('crypto'),
xlsxtojson = require('xlsx-to-json'),
xlstojson = require("xls-to-json");
let fileExtension = require('file-extension');
app.use(bodyParser.json());
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './input/')
},
filename: function (req, file, cb) {
crypto.pseudoRandomBytes(16, function (err, raw) {
cb(null, raw.toString('hex') + Date.now() + '.' + fileExtension(file.mimetype));
});
}
});
let upload = multer({storage: storage}).single('file');
app.post('/sendFile', function(req, res) {
let excel2json;
upload(req,res,function(err){
if(err){
res.json({error_code:401,err_desc:err});
return;
}
if(!req.file){
res.json({error_code:404,err_desc:"File not found!"});
return;
}
if(req.file.originalname.split('.')[req.file.originalname.split('.').length-1] === 'xlsx'){
excel2json = xlsxtojson;
} else {
excel2json = xlstojson;
}
excel2json({
input: req.file.path,
output: "output/"+Date.now()+".json",
lowerCaseHeaders:true
}, function(err, result) {
if(err) {
res.json(err);
} else {
res.json(result);
}
});
})
});
app.get('/',function(req,res){
res.sendFile(__dirname + "/index.html");
});
app.listen('3000', function(){
console.log('Server running on port 3000');
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Excel to Json in nodejs | jsonworld</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="jumbotron text-center">
<h1>Excel to Json in nodejs</h1>
<p>source : <a href="https://jsonworld.com">jsonworld</a></p>
</div>
<div class="container">
<div class="row">
<div class="col-sm-4 col-md-offset-4">
<form id="form" enctype ="multipart/form-data" action="sendFile" method="post">
<div class="form-group">
<input type="file" name="file" class="form-control"/>
<input type="submit" value="Upload" name="submit" class="btn btn-primary" style="float:right; margin-top:30px;">
</form>
</div>
</div>
</div>
</body>
</html>
在此处查找更多信息:jsonworld
console.log("Going to convert...");
没有输出任何内容,则崩溃很可能发生在其他地方。尝试注释掉整个 try-catch 块,并确保第二个日志出现。 - SheetJS