<input type="file" name="file" id="file" onchange="uploadFile(this)"/>
<body>
<script>
var file = document.querySelector('file');
var upload = document.querySelector('upload');
var xhr = new XMLHttpRequest();
function uploadFile(event) {
var formData = new FormData();
formData.append('test-upload', event.files[0]);
xhr.onload = uploadSuccess;
xhr.open('post', '/fileUpload', true);
xhr.send(formData);
}
function uploadSuccess(event) {
if (xhr.readyState === 4) {
console.log(xhr.responseText);
}
}
通宵了代码较乱先不格式化了,
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
const path = require('path')
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/static', express.static('public'))
app.use(multer({ dest: './public/' }).any())
let xlsxrd = require('node-xlsx');
var mysql = require('mysql');
var connection = mysql.createConnection({
host: '',
user: 'root',
password: '',
database: 'test'
});
connection.connect();
app.get('/index.html', function (req, res) {
res.sendFile(__dirname + "/index.tml");
})
app.post('/fileUpload', function (req, res) {
let old = req.files[0].path
let name = req.files[0].path + path.parse(req.files[0].originalname).ext
fs.renameSync(old, './public/' + req.files[0].originalname)
let excelFilePath = './public/' + req.files[0].originalname;
let list = xlsxrd.parse(excelFilePath);
let data = list[0].data.splice(0, 1);
var dats = list[0].data
dats.forEach((item, index) => {
connection.query('insert into user (name,qq,age) values("' + item[0] + '","' + item[1] + '","' + item[2] + '")', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0]);
});
console.log(item);
})
connection.end();
fs.unlinkSync('./public/' + req.files[0].originalname);
res.json({
'imgpath': name
});
})
var server = app.listen(8081, function () {
})
![ajax上传excel文件 express处理数据保存导入数据(实用后台直接批量导入不用一个一个数据添加)_第1张图片](http://img.e-com-net.com/image/info8/9753dac7301041ce92e2ce9565738b90.png)
![ajax上传excel文件 express处理数据保存导入数据(实用后台直接批量导入不用一个一个数据添加)_第2张图片](http://img.e-com-net.com/image/info8/2f41eb49495f4120a5c5a04ed6731e2c.jpg)