安装依赖
npm i express
npm i multer
单文件上传
修改多文件上传代码
node.js
app.post('/upload', upload.single('file'), function (req, res, next) {
req.files.forEach((item,i) => {
console.log(item);
})
res.send('上传成功!')
});
前端代码
let formData = new FormData();
formData.append('file', this.fileList[0].file)
axios({
method: 'post',
url: 'http://127.0.0.1:3000/upload',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest'
},
data: formData
}).then((result) => {
}).catch((err) => {
});
多文件上传
node.js
var fs = require('fs');
var express = require('express');
var multer = require('multer');
var bodyParser = require('body-parser');
var app = express();
//跨域处理
var allowCrossDomain = function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', '*');
res.setHeader('Access-Control-Allow-Headers', '*');
next();
};
app.use(allowCrossDomain);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
/**
* 重命名图片后缀
*/
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/upload/');
},
filename: function (req, file, cb) {
var fileFormat = file.originalname.split('.');
cb(null, file.fieldname + '-' + Date.now() + '.' + fileFormat[fileFormat.length - 1]);
},
});
var upload = multer({ storage: storage });
// var upload = multer({ dest: 'upload/' });
// 多图上传
app.post('/upload', upload.array('file', 8), function (req, res, next) {
req.files.forEach((item,i) => {
console.log(item);
})
res.send('上传成功!')
});
app.listen(3000, () => {
console.log('服务启动3000端口...');
});
前端代码
let formData = new FormData();
this.fileList.forEach(item => {
console.log(item);
formData.append('file', item.file)
});
axios({
method: 'post',
url: 'http://127.0.0.1:3000/upload',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest'
},
data: formData
}).then((result) => {
}).catch((err) => {
});
前端请求数据
- file
后端接收到数据
- req.files